//
//  ViewController.swift
//  MyIdSample
//
//  Created by Javokhir Savriev on 12/10/22.
//

import UIKit
import MyIdSDK

class ViewController: UIViewController {
   
    private let clientIdTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Client ID"
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()
    
    private let passportTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Passport data"
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()
    
    private let dobTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Date of birth"
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()
        
    private let textResult: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.lineBreakMode = .byTruncatingTail
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    private let imageResult: UIImageView = {
        let imageView = UIImageView()
        imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    private var buildType: MyIdBuildMode = .PRODUCTION
    
    private var faceImage: UIImage? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    func loadPayload() throws -> Data {
        let payloadURL = Bundle.main.url(forResource: "payload", withExtension: "json")!
        let payloadData = try Data(contentsOf: payloadURL)
        return payloadData
    }
    
    @objc func buildTypeControlChanged(sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 1 {
            buildType = .DEBUG
        } else {
            buildType = .PRODUCTION
        }
    }
    
    @objc func scanButtonPressed(sender: UIButton) {
        startMyId()
    }
    
    @objc func saveButtonPressed(sender: UIButton) {
        saveImage()
    }
    
    private func startMyId() {
        let config = MyIdConfig()
        config.clientId = "client_id"
        config.clientHash = "client_hash"
        config.clientHashId = "client_hash_id"
        config.passportData = self.passportTextField.text ?? ""
        config.dateOfBirth = self.dobTextField.text ?? ""
        config.buildMode = self.buildType
        
        MyIdClient.start(withConfig: config, withDelegate: self)
    }
    
    private func saveImage() {
        guard let image = faceImage else { return }
        
        ImageSaver().writeToPhotoAlbum(image: image)
    }
}

extension ViewController: MyIdClientDelegate {
    
    func onSuccess(result: MyIdResult) {
        textResult.text = "\(String(describing: result.code))"
        imageResult.image = result.image
        
        faceImage = result.image
    }
    
    func onError(exception: MyIdException) {
        textResult.text = "\(String(describing: exception.message)) - \(String(describing: exception.code))"
    }

    func onUserExited() {
        textResult.text = "User exited"
    }
}

extension ViewController {
    
    private func setupViews() {
        let margins = view.layoutMarginsGuide

        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        
        let buildTypeControl = UISegmentedControl(items: ["PROD", "DEV"])
        buildTypeControl.addTarget(self, action: #selector(buildTypeControlChanged), for: .valueChanged)
        buildTypeControl.selectedSegmentIndex = 0
        buildTypeControl.translatesAutoresizingMaskIntoConstraints = false

        let scanButton = UIButton()
        scanButton.translatesAutoresizingMaskIntoConstraints = false
        scanButton.setTitle("Scan Face Data", for: .normal)
        scanButton.setTitleColor(.blue, for: .normal)
        scanButton.addTarget(self, action: #selector(scanButtonPressed), for: .touchUpInside)
        
        let saveButton = UIButton()
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.setTitle("Save Image", for: .normal)
        saveButton.setTitleColor(.red, for: .normal)
        saveButton.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .leading
        stackView.spacing = 16
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.addArrangedSubview(clientIdTextField)
        stackView.addArrangedSubview(passportTextField)
        stackView.addArrangedSubview(dobTextField)
        stackView.addArrangedSubview(scanButton)
        stackView.addArrangedSubview(saveButton)
        stackView.addArrangedSubview(textResult)
        stackView.addArrangedSubview(imageResult)
        
        scrollView.addSubview(stackView)
        view.addSubview(scrollView)
        
        NSLayoutConstraint.activate([
            scrollView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
            scrollView.topAnchor.constraint(equalTo: margins.topAnchor),
            scrollView.bottomAnchor.constraint(equalTo: margins.bottomAnchor)
        ])
        
        NSLayoutConstraint.activate([
            stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            stackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 20),
            stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
        ])
        
        NSLayoutConstraint.activate([
            clientIdTextField.widthAnchor.constraint(equalTo: stackView.widthAnchor),
            passportTextField.widthAnchor.constraint(equalTo: stackView.widthAnchor),
            dobTextField.widthAnchor.constraint(equalTo: stackView.widthAnchor),
            scanButton.centerXAnchor.constraint(equalTo: stackView.centerXAnchor),
            saveButton.centerXAnchor.constraint(equalTo: stackView.centerXAnchor),
        ])
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}
