//
//  ViewController.swift
//  LivenessSDKSwiftDemo
//
//  Created by advance on 2021/7/21.
//

import UIKit
import AAILivenessUI

public class ViewController: UIViewController {
    private var _testType: Int = 0

    public override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let label = UILabel(frame: CGRect(x: 0, y: 80, width: UIScreen.main.bounds.size.width, height: 40))
        label.text = "SDK version: \(AAILivenessSDK.sdkVersion())"
        self.view.addSubview(label)
        
        self.addButton("Default test", CGRect(x: 40, y: 140, width: 140, height: 40), #selector(tapSDKBtnAction))
        self.addButton("CustomUI test 03", CGRect(x: 40, y: 200, width: 200, height: 40), #selector(tapCustomUIBtn03Action))
    }
    
    func addButton(_ title: String, _ frame: CGRect, _ action: Selector) {
        let btn = UIButton(type: .custom)
        btn.frame = frame
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(.red, for: .normal)
        btn.addTarget(self, action: action, for: .touchUpInside)
        self.view.addSubview(btn)
    }

    @objc func tapSDKBtnAction() {
        _testType = 0
        
        showSDK(licenseContent: fetchLicense())
    }
    
    @objc func tapCustomUIBtn03Action() {
        _testType = 3
        showSDK(licenseContent: fetchLicense())
    }
    
    func fetchLicense() -> String {
        // Load License
        /*
         The license content is obtained by your server calling our openapi.
         In order to facilitate the demonstration of this SDK, we directly put the content of the license into the file, in fact, you should call your server api to get the license content.
         */
        guard let path = Bundle.main.path(forResource: "SDK-DEMO-LICENSE", ofType: nil) else {
            print("SDK-DEMO-LICENSE file not exist!")
            return ""
        }

        var demoLicenseContent = ""
        do {
            var content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
            content = content.trimmingCharacters(in: .whitespacesAndNewlines)
            demoLicenseContent = content
        } catch {}
        
        return demoLicenseContent
    }
    
    func showSDK(licenseContent: String) {
        if licenseContent.isEmpty {
            print("⚠️ license is empty")
            return
        }
        
        // 1. Specify the market to initialize the SDK
        // Note if you have subscribed to the Global liveness service,
        // you should configure the `isGlobalService` property of the config object to true.
        let config = AAILDLicenseModeConfig()
        config.market = .indonesia
        config.isGlobalService = false
        AAILivenessSDK.initWith(config)
        
        // 2. Check license
        let checkResult = AAILivenessSDK.configLicenseAndCheck(licenseContent)
        if checkResult != "SUCCESS" {
            if checkResult == "LICENSE_EXPIRE" {
                print("LICENSE_EXPIRE: please call your server's api to generate a new license")
            } else if checkResult == "APPLICATION_ID_NOT_MATCH" {
                print("APPLICATION_ID_NOT_MATCH: please bind your app's bundle identifier on our cms website, then recall your server's api to generate a new license")
            } else {
                print("\(checkResult)")
            }
            return;
        }
        
        // license is valid, show SDK page
        
        // Demo: Push default liveness view controller
        if _testType == 0 {
            let vc = AAILivenessViewController()
            // Refer to the user guide document for additional
            // configuration options related to this view controller.
            // ...
            vc.detectionSuccessBlk = {(rawVC, result) in
                let livenessId = result.livenessId
                let bestImg = result.img
                let size = bestImg.size
                // Get eventId(You should save this ID in case of tracking problems).
                let eventId = result.eventId
                print(">>>>>livenessId: \(livenessId), imgSize: \(size.width), \(size.height), eventId:\(eventId)")
                // Do something... (e.g., call anti-spoofing api to get score)
                
                rawVC.navigationController?.popViewController(animated: true)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        // Demo: Present custom liveness view controller
        if _testType == 3 {
            let vc = AAICustomLD03Controller()
            // Refer to the user guide document for additional
            // configuration options related to this view controller.
            // ...
            vc.hudBrandColor = .red
            vc.title = "Take a Selfie"
            vc.language = "id"
            
            let livenessConfig = vc.livenessConfig
            livenessConfig.highlightAvatarBorderColor = .brown
            livenessConfig.innerAnimatedEllipseLineColor = .brown
            
            vc.detectionSuccessBlk = {(rawVC, result) in
                let livenessId = result.livenessId
                let bestImg = result.img
                let size = bestImg.size
                // Get eventId(You should save this ID in case of tracking problems).
                let eventId = result.eventId
                print(">>>>>livenessId: \(livenessId), imgSize: \(size.width), \(size.height), eventId:\(eventId)")
                // Do something... (e.g., call anti-spoofing api to get score)
                
                rawVC.presentingViewController?.dismiss(animated: true, completion: nil)
            }
            
            let navc = UINavigationController(rootViewController: vc)
            navc.isNavigationBarHidden = true
            navc.modalPresentationStyle = .fullScreen
            self.present(navc, animated: true, completion: nil)
        }
    }
}

