//
//  AppDelegate.swift
//  TestQmeraLite
//
//  Created by Qindi on 29/11/21.
//

import UIKit
import NexilisLite
import NotificationBannerSwift

struct AppFontName {
    static let regular = "Poppins-Regular"
    static let bold = "Poppins-SemiBold"
    static let italic = "Poppins-MediumItalic"
}

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

extension UIFont {
    static var isOverrided: Bool = false
    static let FONT_SELECT = 0

    @objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.regular, size: size)!
    }

    @objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.bold, size: size)!
    }

    @objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.italic, size: size)!
    }

    @objc convenience init(myCoder aDecoder: NSCoder) {
        guard
            let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
            let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
                self.init(myCoder: aDecoder)
                return
        }
        var fontName = ""
        switch fontAttribute {
        case "CTFontRegularUsage":
            fontName = AppFontName.regular
        case "CTFontEmphasizedUsage", "CTFontBoldUsage":
            fontName = AppFontName.bold
        case "CTFontObliqueUsage":
            fontName = AppFontName.italic
        default:
            fontName = AppFontName.regular
        }
        self.init(name: fontName, size: fontDescriptor.pointSize)!
    }

    class func overrideInitialize() {
        guard self == UIFont.self, !isOverrided, FONT_SELECT == 0 else { return }

        // Avoid method swizzling run twice and revert to original initialize function
        isOverrided = true

        if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
            let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
            method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
        }

        if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
            let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
            method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
        }

        if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
            let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
            method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
        }

        if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
            let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
            method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
        }
    }
}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    override init() {
        super.init()
        UIFont.overrideInitialize()
    }
    
    func transparentNavbar(){
        // Sets background to a blank/empty image
            UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
            // Sets shadow (line below the bar) to a blank image
            UINavigationBar.appearance().shadowImage = UIImage()
            // Sets the translucent background color
            UINavigationBar.appearance().backgroundColor = .clear
            // Set translucent. (Default value is already true, so this can be removed if desired.)
            UINavigationBar.appearance().isTranslucent = true
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // Nexilis.connect(apiKey: "09ED34439CFE435E5D528E73F2D3DC1B23307B56EAB28A4883700D47BB5ADE07", delegate: self, showButton: false)
//        Nexilis.connect(apiKey: "E6FF534BDA45A78619488E44AC90592327DDF33ACF6213A58DB55B78300BA8EE", delegate: self, showButton: false)
        if !CheckConnection.isConnectedToNetwork() {
            let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
            imageView.tintColor = .white
            let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
            banner.show()
        } else {
            var showButton = false
            if PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_FLOATING || PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_MIX {
                showButton = true
            }
            Nexilis.connect(apiKey: "***REPLACE***WITH***YOUR***ACCOUNT***", delegate: self, showButton: showButton, fromMAB: true) //AA6164AA13F0A6262677AC7443C37E3F6F0A342E8BEE84B700CB59C876166FE0(AWS) //36BCB99AA3885165E64ECC50591C4DA5072A25B2E7BAADA5A1B57E18737FF88C(CBN)
            if let response = Nexilis.writeSync(message: getPrefs(key: ""), timeout: 5000) {
                if response.mBodies[CoreMessage_TMessageKey.ERRCOD] == "00" {
                    let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
                    if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
                        UserDefaults.standard.removeObject(forKey: "app_builder_url_first_tab")
                        UserDefaults.standard.removeObject(forKey: "app_builder_url_third_tab")
                        UserDefaults.standard.removeObject(forKey: "app_builder_custom_tab")
                        UserDefaults.standard.removeObject(forKey: "app_builder_url_base")
                        UserDefaults.standard.removeObject(forKey: "app_builder_url_qms")
                        UserDefaults.standard.removeObject(forKey: "app_builder_icon_dock")
                        UserDefaults.standard.removeObject(forKey: "app_builder_icon_ss")
                        UserDefaults.standard.removeObject(forKey: "app_builder_background")
                        UserDefaults.standard.removeObject(forKey: "app_builder_compressor")
                        for j in json {
                            if let firstTab = j["app_builder_url_first_tab"] as? String {
                                PrefsUtil.setURLFirstTab(value: firstTab)
                                ViewController.sURL = firstTab
                            }
                            if let thirdTab = j["app_builder_url_third_tab"] as? String {
                                PrefsUtil.setURLThirdTab(value: thirdTab)
                                ViewController.tab3 = thirdTab
                            }
                            if let customTab = j["app_builder_custom_tab"] as? String {
                                PrefsUtil.setCustomTab(cust: customTab)
                            }
                            if let urlBase = j["app_builder_url_base"] as? String {
                                PrefsUtil.setURLBase(value: urlBase)
                            }
                            if let urlQMS = j["app_builder_url_qms"] as? String {
                                PrefsUtil.setURLQMS(value: urlQMS)
                            }
                            if let iconDock = j["app_builder_icon_dock"] as? String {
                                PrefsUtil.setIconDock(value: iconDock)
                            }
                            if let iconSS = j["app_builder_icon_ss"] as? String {
                                PrefsUtil.setIconSS(value: iconSS)
                            }
                            if let background = j["app_builder_background"] as? String {
                                PrefsUtil.setBackground(value: background)
                            }
                            if let background = j["app_builder_compressor"] as? String {
                                PrefsUtil.setCompressor(value: background)
                            }
                        }
                    }
                }
            }
        }
        let tabBarAppearance: UITabBarAppearance = UITabBarAppearance()
        tabBarAppearance.configureWithDefaultBackground()
        if Bundle.main.displayName == "DigiNetS" {
            tabBarAppearance.backgroundColor = .black.withAlphaComponent(0.7)
        }
        if #available(iOS 13.0, *) {
            UITabBar.appearance().standardAppearance = tabBarAppearance
        }
        if #available(iOS 15.0, *) {
            UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
        }
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    
    func getPrefs(key: String) -> TMessage {
        let tMessage = NexilisLite.TMessage()
        let me = UserDefaults.standard.string(forKey: "me")
        tMessage.mCode = "PPR"
        tMessage.mStatus = CoreMessage_TMessageUtil.getTID()
        tMessage.mBodies[CoreMessage_TMessageKey.F_PIN] = me
        tMessage.mBodies[CoreMessage_TMessageKey.KEY] = key
        return tMessage
    }


}

extension AppDelegate: ConnectDelegate {
    
    func onSuccess(userId: String) {
        print(#function, "userId: \(userId)")
    }
    
    func onFailed(error: String) {
        print(#function, "error: \(error)")
    }
    
}

