//
//  ViewController.swift
//  Demo-DeepLink
//
//  Created by kirill on 12/10/19.
//  Copyright © 2019 Inspector Cloud. All rights reserved.
//

import UIKit

import ICDeepLink

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var schemeTextField: UITextField!
    @IBOutlet weak var tokenTextField: UITextField!
    @IBOutlet weak var userIdTextField: UITextField!
    @IBOutlet weak var customerIdTextField: UITextField!
    @IBOutlet weak var visitIdTextField: UITextField!
    @IBOutlet weak var filterTextField: UITextField!
    @IBOutlet weak var taskTypeCidTextField: UITextField!
    @IBOutlet weak var readOnlySwitch: UISwitch!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        schemeTextField.text = ICDeepLinkService.shared.scheme
        userIdTextField.text = ICDeepLinkService.shared.agentId
        visitIdTextField.text = UUID().uuidString
        
        if let scheme = UserDefaults.standard.string(forKey: "scheme") {
            ICDeepLinkService.shared.scheme = scheme
            schemeTextField.text = scheme
        }
        
        if let token = UserDefaults.standard.string(forKey: "token") {
            ICDeepLinkService.shared.token = token
            tokenTextField.text = token
        }
        
        if let agentId = UserDefaults.standard.string(forKey: "agentId") {
            ICDeepLinkService.shared.agentId = agentId
            userIdTextField.text = agentId
        }
        
        if let customerId = UserDefaults.standard.string(forKey: "customerId") {
            customerIdTextField.text = customerId
        }
        
        if let visitId = UserDefaults.standard.string(forKey: "visitId") {
            visitIdTextField.text = visitId
        }
        
        if let filter = UserDefaults.standard.string(forKey: "filter") {
            filterTextField.text = filter
        }
        
        if let taskTypeCid = UserDefaults.standard.string(forKey: "taskTypeCid") {
            taskTypeCidTextField.text = taskTypeCid
        }
        
        readOnlySwitch.isOn = UserDefaults.standard.bool(forKey: "readonly")
        
        ICDeepLinkService.shared.delegate = self
        
        [schemeTextField, tokenTextField, userIdTextField, customerIdTextField,
         visitIdTextField, filterTextField, taskTypeCidTextField].forEach { $0?.delegate = self }
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tapGesture.cancelsTouchesInView = false
        view.addGestureRecognizer(tapGesture)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        guard let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        let inset = frame.height - view.safeAreaInsets.bottom
        scrollView.contentInset.bottom = inset
        scrollView.verticalScrollIndicatorInsets.bottom = inset
    }
    
    @objc private func keyboardWillHide(_ notification: Notification) {
        scrollView.contentInset.bottom = 0
        scrollView.verticalScrollIndicatorInsets.bottom = 0
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    
    
    @IBAction func changedSchemeAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "scheme")
        ICDeepLinkService.shared.scheme = sender.text
    }
    
    @IBAction func changedTokenAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "token")
        ICDeepLinkService.shared.token = sender.text
    }
    
    @IBAction func changedUserAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "agentId")
        ICDeepLinkService.shared.agentId = sender.text
    }
    
    @IBAction func changedCustomerAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "customerId")
    }
    
    @IBAction func changedVisitAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "visitId")
    }
    
    @IBAction func changedFilterAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "filter")
    }
    
    @IBAction func changedTaskTypeCidAction(_ sender: UITextField) {
        UserDefaults.standard.setValue(sender.text ?? "", forKey: "taskTypeCid")
    }
    
    @IBAction func readOnlyAction(_ sender: UISwitch) {
        UserDefaults.standard.setValue(sender.isOn, forKey: "readonly")
    }
    
    @IBAction func syncAction(_ sender: Any) {
        let customerIds = (customerIdTextField.text ?? "").split(separator: ",").map { String($0) }
        ICDeepLinkService.shared.sync(customerIds: customerIds)
    }
    
    @IBAction func openAction(_ sender: Any) {
        ICDeepLinkService.shared.openVisit(visitId: visitIdTextField.text ?? "",
                                    customerId: customerIdTextField.text ?? "",
                                    isReadonly: readOnlySwitch.isOn,
                                    filter: filterTextField.text ?? "",
                                    taskTypeCid: taskTypeCidTextField.text ?? "")
    }
}


extension ViewController: ICDeepLinkDelegate {
    func receive(customerId: String, totalImages: Int) {
        print("")
    }
    
    func sync(status: Bool) {
        print("")
    }
    
    func error(_ error: ICDeepLinkError) {
        print("")
    }
}

extension ViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
            guard let self else { return }
            let rect = textField.convert(textField.bounds, to: self.scrollView).insetBy(dx: 0, dy: -16)
            self.scrollView.scrollRectToVisible(rect, animated: true)
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
