VerificationViewController.swift 7.6 KB
//
//  ViewController.swift
//  InterQR-Internship
//
//  Created by Дмитрий Тимофеев on 30.05.2022.
//

import UIKit

class VerificationViewController: UIViewController {
    var networkManager = AuthNetworkManager()
    var isKeyboardAppear = false
    private let mainView = VerificationView()
    
    lazy var phonePickerModels: [PhonePickerModel] = {
        var models: [PhonePickerModel] = []
        
        for (code, value) in PhoneService.phones
        {
            models.append(.init(code: code, countryCode: value.1, title: value.0, icon: value.2))
        }
        return models
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func loadView() {
        view = mainView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initViewController()
    }
    
    private func initViewController() {
        mainView.phonePickerView.phoneNumberPicker.delegate = self
        mainView.phonePickerView.phoneNumberPicker.dataSource = self
        
        mainView.phoneNumberButton.addTarget(self, action: #selector(didCheckboxTapped(_:)), for: .touchUpInside)
        mainView.emailButton.addTarget(self, action: #selector(didCheckboxTapped(_:)), for: .touchUpInside)
        mainView.showPickerButton.addTarget(self, action: #selector(didshowPickerButtonTapped(_:)), for: .touchUpInside)
        mainView.phonePickerView.selectButton.addTarget(self, action: #selector(didshowPickerButtonTapped(_:)), for: .touchUpInside)
        mainView.phonePickerView.titleButton.addTarget(self, action: #selector(didshowPickerButtonTapped(_:)), for: .touchDragInside)
        
        mainView.continueButton.addTarget(self, action: #selector(didTapContinueButton), for: .touchUpInside)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func networking() {
        guard let startUrl = URL(string: Constants.APIRoutes.startURL.urlString) else { return }
        guard let startModel = startModelFilling() else { return }
        networkManager.startRequest(startUrl, model: startModel) { response in
            print("2️⃣✅\(response.message)✅")
        } fail: { error in
            print("2️⃣❌\(error)❌")
        }
    }
    
    func startModelFilling() -> StartRequestModel? {
        let number = mainView.phoneTextField.text
        let email = mainView.emailTextField.text
        if number == nil {
            return StartRequestModel(emailOrNumber: (String(describing: email)))
        } else {
            return StartRequestModel(emailOrNumber: (String(describing: number)))
        }
    }
}

//MARK: helpers and handlers
extension VerificationViewController {
    
}

//MARK: targets
extension VerificationViewController {
    @objc private func didCheckboxTapped(_ sender: Checkbox) {
        mainView.isChanged ? mainView.handleUI(true) : mainView.handleUI(false)
        mainView.isChanged.toggle()
    }
    
    @objc private func didshowPickerButtonTapped(_ sender: UIButton) {
        mainView.isShow ? mainView.showPickerView() : mainView.hidePickerView()
        mainView.isShow.toggle()
    }
    
    @objc private func didTapContinueButton() {
        didShowCodeVerificationVC()
    }
    
    private func didShowCodeVerificationVC() {
        guard let email = mainView.emailTextField.text else { return }
        guard let number = mainView.phoneTextField.text else { return }
        let userCode: String = .Text.userCode
        if email.isEmpty || number.isEmpty{
            let alert = UIAlertController(title: "Enter email or number fields", message: "", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            present(alert, animated: true)
        } else { if email == userCode || number == userCode {
            let vc = CodeVerificationViewController()
            vc.navigationItem.hidesBackButton = true
            navigationController?.pushViewController(vc, animated: true)
            networking()
        } else { if email != userCode || number != userCode {
            let alert = UIAlertController(title: "User does not exist", message: "", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            present(alert, animated: true)
        }
        }
        }
    }
    
    @objc private func keyboardWillShow(notification: NSNotification) {
        let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        if !isKeyboardAppear {
            UIView.animate(withDuration: duration ?? 0) {
                self.mainView.chooseLabel.snp.updateConstraints { make in
                    make.top.equalTo(self.mainView.shieldImage.snp.bottom).offset(0)
                }
                self.mainView.dividingLineView.snp.updateConstraints {
                    $0.top.equalTo(self.mainView.emailButton.snp.bottom).offset(10)
                }
                self.mainView.enterChosenAuthenticatorLabel.snp.updateConstraints {
                    $0.top.equalTo(self.mainView.dividingLineView.snp.bottom).offset(5)
                }
                self.mainView.layoutIfNeeded()
            }
            isKeyboardAppear = true
        }
    }
    
    @objc private func keyboardWillHide(notification: NSNotification) {
        let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        
        if isKeyboardAppear {
            
            UIView.animate(withDuration: duration ?? 0) {
                self.mainView.chooseLabel.snp.updateConstraints { make in
                    make.top.equalTo(self.mainView.shieldImage.snp.bottom).offset(52)
                }
                self.mainView.dividingLineView.snp.updateConstraints {
                    $0.top.equalTo(self.mainView.emailButton.snp.bottom).offset(41)
                }
                self.mainView.enterChosenAuthenticatorLabel.snp.updateConstraints {
                    $0.top.equalTo(self.mainView.dividingLineView.snp.bottom).offset(39)
                }
                self.mainView.layoutIfNeeded()
            }
            isKeyboardAppear = false
        }
    }
}

extension VerificationViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return phonePickerModels.count
        
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        60
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let model = phonePickerModels[row]
        return PickerView.create(icon: model.icon, title: model.title, code: model.countryCode)
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        pickerView.subviews[1].backgroundColor = .clear
        let model = phonePickerModels[row]
        mainView.phoneTextField.text = "\(model.countryCode)"
        mainView.flagPickerView.image = model.icon
    }
}