//
//  Stars.swift
//  MVMCoreUI
//
//  Created by Lekshmi S on 21/09/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

open class Stars: View {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    private var stack = UIStackView()
    public var starsModel: StarsModel? {
        return model as? StarsModel
    }
    private var delegateObject: MVMCoreUIDelegateObject?
    private let itemSpacing: CGFloat = 3.0
    private var heightConstraint: NSLayoutConstraint?
    private var starsFilledValue: Float = 0
    
    //--------------------------------------------------
    // MARK: - MVMCoreViewProtocol
    //--------------------------------------------------
    open override func setupView() {
        super.setupView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .horizontal
        stack.spacing = itemSpacing
        addSubview(stack)
        NSLayoutConstraint.constraintPinSubview(toSuperview: stack)
        heightConstraint = heightAnchor.constraint(equalToConstant: 30)
        heightConstraint?.isActive = true
        isAccessibilityElement = true
        updateAccessibilityLabel()
    }
    
    @objc override open func updateView(_ size: CGFloat) {
        super.updateView(size)
        stack.updateView(size)
    }
    
    //--------------------------------------------------
    // MARK: - MoleculeViewProtocol
    //--------------------------------------------------
    open override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        self.delegateObject = delegateObject
        createStars()
        updateStars()
        updateAccessibilityLabel()
    }
    
    public override func reset() {
        stack.subviews.forEach({$0.removeFromSuperview()})
        super.reset()
    }
    
    //------------------------------------------------------
    // MARK: - Methods
    //------------------------------------------------------
    func createStars() {
        guard let starsModel = starsModel else { return }
        for starModel in starsModel.stars {
            let star = Star(model: starModel, delegateObject, nil)
            star.isAccessibilityElement = false
            stack.addArrangedSubview(star)
        }
        heightConstraint?.constant = starsModel.size
    }
    
    func updateStars() {
        guard let starsModel = starsModel else { return }
        let percentRequiredToFillStarFully = CGFloat(100/(stack.arrangedSubviews.count))
        let numberOfFilledStars = Int(starsModel.percent/percentRequiredToFillStarFully)
        starsFilledValue = Float(numberOfFilledStars)
        for case let (index, star as Star) in stack.arrangedSubviews.enumerated() {
            //Star model colors should take priority over stars.
            if let borderColor = starsModel.borderColor?.cgColor, star.starModel?.borderColor == nil {
                star.borderColor = borderColor
            }
            if let fillColor = starsModel.fillColor?.uiColor, star.starModel?.fillColor == nil {
                star.fillColor = fillColor
            }
            if let backgroundColor = starsModel.starBackgroundColor?.uiColor, star.starModel?.backgroundColor == nil {
                star.backgroundColor = backgroundColor
            }
            
            //Fill the stars based on percentage. Ex: if there were 4 stars, 75 percent is 3 full stars
            if index < numberOfFilledStars {
                star.percent = 100
            } else if index == numberOfFilledStars {
                let remainingProgress = (starsModel.percent).truncatingRemainder(dividingBy: percentRequiredToFillStarFully)
                let fillPercent = remainingProgress/percentRequiredToFillStarFully
                starsFilledValue += Float(fillPercent)
                star.percent = fillPercent * 100
            } else {
                star.percent = 0
            }
            star.size = starsModel.size
        }
    }
    
    // MARK: - Accessibility
    func updateAccessibilityLabel() {
        accessibilityLabel = String(format: MVMCoreUIUtility.hardcodedString(withKey: "stars_filled") ?? "", starsFilledValue, stack.arrangedSubviews.count)
    }
}
