//
//  ProgressBar.swift
//  MVMCoreUI
//
//  Created by Panth Patel on 5/3/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import Foundation


@objcMembers open class ProgressBar: UIProgressView, MVMCoreViewProtocol, MoleculeViewProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    var progressBarModel: ProgressBarModel?
    
    var thickness: CGFloat = 8.0 {
        willSet(newValue) {
            heightAnchor.constraint(equalToConstant: newValue).isActive = true
            
            if progressBarModel?.roundedCorners ?? false {
                layer.cornerRadius = newValue / 2.0
            } else {
                progressViewStyle = .bar
            }
        }
    }
    
    //--------------------------------------------------
    // MARK: - Initializers
    //--------------------------------------------------
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    
    public init() {
        super.init(frame: .zero)
        setupView()
    }
    
    //--------------------------------------------------
    // MARK: - Lifecycle
    //--------------------------------------------------
    
    public func setupView() {
        
        clipsToBounds = true
        translatesAutoresizingMaskIntoConstraints = false
        thickness = 8
        progress = 0
        progressTintColor = .mfCerulean()
        trackTintColor = .mvmCoolGray3
    }
    
    public func updateView(_ size: CGFloat) { }
    
    //--------------------------------------------------
    // MARK: - MVMCoreViewProtocol
    //--------------------------------------------------
    
    public func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        
        guard let progressBarModel = model as? ProgressBarModel else { return }
        
        self.progressBarModel = progressBarModel
        thickness = progressBarModel.thickness ?? 8
        progress = Float((progressBarModel.percent) / 100.0)
        progressTintColor = progressBarModel.color.uiColor
        
        if let backgroundColor = progressBarModel.backgroundColor {
            trackTintColor = backgroundColor.uiColor
        }
    }
    
    public func reset() {
        
        thickness = 8
        progress = 0
        progressTintColor = .mfCerulean()
        trackTintColor = .mvmCoolGray3
    }
    
    public static func estimatedHeight(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?) -> CGFloat? {
        return 8
    }
}
