import Flutter
import UIKit
import AppTrackingTransparency

public class SwiftGuruPlatformDataPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "app.guru.guru_platform_data", binaryMessenger: registrar.messenger())
        let instance = SwiftGuruPlatformDataPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let arguments = call.arguments as? [String: Any] ?? [String: Any]()
        NSLog("[PDC] handle method:\(call.method)")
        switch call.method {
        case "requestTrackingAuthorization":
            if #available(iOS 14, *) {
                self.requestIDFA(handler: { status in
                    result(status.rawValue)
                })
            } else {
                // Fallback on earlier versions
                result(0)
            }
            break
        case "getTrackingAuthorizationStatus":
            if #available(iOS 14, *) {
                result(self.getTrackingAuthorizationStatus().rawValue)
            } else {
                // Fallback on earlier versions
                result(-1)
            };
            break;
        case "jumpToAppPrivacySettings":
            self.jumpToAppPrivacySettings()
            result(true)
            break;
        case "get_brightness":
            let brightness = UIScreen.main.brightness
            NSLog("[PDC] ==> get_brightness \(brightness)")
            result(brightness)
            break;
        case "set_brightness":
            let brightness = arguments["brightness"] as? Double ?? 1.0
            NSLog("[PDC] ==> set_brightness \(brightness) \(arguments["brightness"])")
            UIScreen.main.brightness = CGFloat(brightness)
            result(true)
            break;
        case "is_kept_screen_on":
            let isIdleTimerDisabled = UIApplication.shared.isIdleTimerDisabled
            result(isIdleTimerDisabled)
            break;
        case "keep_screen_on":
            let on = arguments["on"] as? Bool
            if (on == nil) {
                result(false)
            } else {
                UIApplication.shared.isIdleTimerDisabled = on!
                result(true)
            }
            break;
        case "getLocalTimezone":
            let timeZone = TimeZone.current
            let tzName = timeZone.identifier
            result(tzName)
            break;
        case "getAvailableTimezones":
            let knownTimeZoneNames = TimeZone.knownTimeZoneIdentifiers
            result(knownTimeZoneNames)
            break;
        case "get_purpose_consents":
            let purposeConsents = UserDefaults.standard.string(forKey: "IABTCF_PurposeConsents")
            // Purposes are zero-indexed. Index 0 contains information about Purpose 1.
            result(purposeConsents)
            break;
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    func jumpToAppPrivacySettings() {
        if let appSetting = URL(string:UIApplication.openSettingsURLString) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(appSetting, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(appSetting)
            }
        }
    }
    
    @available(iOS 14, *)
    func requestIDFA(handler: @escaping (ATTrackingManager.AuthorizationStatus) -> Void) {
        // notDetermined = 0
        // restricted = 1
        // denied = 2
        // authorized = 3
        //        let _result = result
        ATTrackingManager.requestTrackingAuthorization(completionHandler: handler)
    }
    
    @available(iOS 14, *)
    func getTrackingAuthorizationStatus()-> ATTrackingManager.AuthorizationStatus {
        return ATTrackingManager.trackingAuthorizationStatus;
    }
}
