//
//  DigitBox.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 10/15/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit

@objc protocol DigitBoxProtocol {
    @objc optional func digitFieldDidDelete(_ textField: TextField?)
}


@objcMembers open class DigitBox: EntryFieldContainer, UITextFieldDelegate, TextInputDidDeleteProtocol {
    //--------------------------------------------------
    // MARK: - Outlets
    //--------------------------------------------------
    
    let digitField: TextField = {
        let textField = TextField()
        textField.isAccessibilityElement = true
        textField.setContentCompressionResistancePriority(.required, for: .vertical)
        textField.setContentCompressionResistancePriority(.required, for: .horizontal)
        textField.textAlignment = .center
        textField.font = Styler.Font.RegularBodyLarge.getFont()
        textField.keyboardType = .numberPad
        return textField
    }()
    
    //--------------------------------------------------
    // MARK: - Stored Properties
    //--------------------------------------------------
    
    private var previousSize: CGFloat = 0.0
    
    // Default dimensions of the DigitBox
    static let size: CGSize = CGSize(width: 39, height: 44)
    
    //--------------------------------------------------
    // MARK: - Computed Properties
    //--------------------------------------------------
    
    public override var showError: Bool {
        get { super.showError }
        set (error) {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                
                self.borderStrokeColor = error ? .mvmOrange : .mvmCoolGray3
                
                let barHeight: CGFloat = self.showError ? 4 : 1
                self.bottomBar?.frame = CGRect(x: 0, y: self.bounds.height - barHeight, width: self.bounds.width, height: barHeight)
                self.bottomBar?.backgroundColor = self.showError ? UIColor.mvmOrange.cgColor : UIColor.mvmBlack.cgColor
                
                self.setNeedsDisplay()
                self.layoutIfNeeded()
            }
            super.showError = error
        }
    }
    
    //--------------------------------------------------
    // MARK: - Delegate
    //--------------------------------------------------
    
    weak var digitBoxDelegate: DigitBoxProtocol?
    
    //--------------------------------------------------
    // MARK: - Constraints
    //--------------------------------------------------
    
    private weak var widthConstraint: NSLayoutConstraint?
    private weak var heightConstraint: NSLayoutConstraint?
    
    //--------------------------------------------------
    // MARK: - Lifecycle
    //--------------------------------------------------
    
    open override func setupView() {
        super.setupView()
        
        addSubview(digitField)
        digitField.delegate = self
        digitField.didDeleteDelegate = self
        
        widthConstraint = widthAnchor.constraint(equalToConstant: DigitBox.size.width)
        widthConstraint?.isActive = true
        heightConstraint = heightAnchor.constraint(equalToConstant: DigitBox.size.height)
        heightConstraint?.isActive = true
        
        NSLayoutConstraint.activate([
            digitField.topAnchor.constraint(equalTo: topAnchor, constant: Padding.Three),
            digitField.leadingAnchor.constraint(equalTo: leadingAnchor),
            bottomAnchor.constraint(equalTo: digitField.bottomAnchor, constant: Padding.Three),
            trailingAnchor.constraint(equalTo: digitField.trailingAnchor),
            digitField.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
        
        if let bottomBar = bottomBar {
            layer.addSublayer(bottomBar)
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(callTextField))
        addGestureRecognizer(tap)
        
        updateView(MVMCoreUIUtility.getWidth())
    }
    
    @objc public func textInputDidDelete() {
        
        digitBoxDelegate?.digitFieldDidDelete?(digitField)
    }
    
    @objc open override func layoutSubviews() {
        super.layoutSubviews()
        
        let barHeight: CGFloat = showError ? 4 : 1
        bottomBar?.frame = CGRect(x: 0, y: bounds.height - barHeight, width: bounds.width, height: barHeight)
    }
    
    @objc open override func reset() {
        super.reset()
        
        backgroundColor = .clear
        digitField.font = Styler.Font.RegularBodyLarge.getFont()
    }
    
    //--------------------------------------------------
    // MARK: - Methods
    //--------------------------------------------------
    
    @objc public func callTextField() {
        
        digitField.becomeFirstResponder()
    }
    
    @objc public override func updateView(_ size: CGFloat) {
        super.updateView(size)
        
        if !MVMCoreGetterUtility.fequal(a: Float(size), b: Float(previousSize)) {
            
            var width: CGFloat = 0
            var height: CGFloat = 0
            var pointSize: CGFloat = 13
            
            let sizeObject = MFSizeObject(standardBlock: {
                width = 39
                height = 44
                pointSize = 16
                
            }, smalliPhone: {
                width = 35
                height = 38
                pointSize = 13
                
            }, standardiPadPortraitBlock: {
                width = 59
                height = 74
                pointSize = 32
            })
            
            sizeObject?.performBlockBase(onSize: size)
            widthConstraint?.constant = width
            heightConstraint?.constant = height
            digitField.font = MFFonts.mfFontDSRegular(pointSize)
            previousSize = size
        }
        
        setNeedsLayout()
    }
}
