//
//  DashLine_Swift.swift
//  MVMCoreUI

//  Created by Chris Yang on 2/11/16.
//  Converted by Christiano, Kevin on 3/18/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import MVMCore


open class DashLine: View {
    //------------------------------------------------------
    // MARK: - Properties
    //------------------------------------------------------
    
    var dashModel: DashLineModel? {
        get { return model as? DashLineModel }
    }
    
    //TODO: Need this for BAU. Can remove once we fix BAU
    public var dashColor: UIColor?
    
    @objc private var dashLayer: CAShapeLayer?
    
    //------------------------------------------------------
    // MARK: - Lifecycle
    //------------------------------------------------------
    
    @objc override open func updateView(_ size: CGFloat) {
        
        DispatchQueue.main.async { [weak self] in
            self?.setNeedsDisplay()
        }
    }
    
    @objc override open func draw(_ rect: CGRect) {
        
        let dashLayer = CAShapeLayer()
        dashLayer.backgroundColor = UIColor.clear.cgColor
        dashLayer.frame = bounds
        
        layer.sublayers?.forEach { $0.removeFromSuperlayer() }
        layer.addSublayer(dashLayer)
        
        let path = UIBezierPath()
        path.move(to: CGPoint(x: dashLayer.frame.origin.x, y: dashLayer.frame.size.height / 2.0)) //add yourStartPoint here
        path.addLine(to: CGPoint(x: dashLayer.frame.size.width, y: 0))
        path.stroke()
        
        dashLayer.strokeStart = 0
        dashLayer.lineWidth = 1
        dashLayer.lineJoin = .miter
        dashLayer.lineCap = .round
        dashLayer.lineDashPattern = [NSNumber(value: 2), NSNumber(value: 2)]
        dashLayer.path = path.cgPath
        dashLayer.strokeColor = dashColor?.cgColor
        dashLayer.fillColor = UIColor.clear.cgColor
        dashLayer.backgroundColor = (dashModel?.inverted ?? false) ? UIColor.mvmBlack.cgColor : backgroundColor?.cgColor ?? UIColor.mvmWhite.cgColor
        self.dashLayer = dashLayer
    }
    
    //------------------------------------------------------
    // MARK: - Atomization
    //------------------------------------------------------
    
    @objc open override func reset() {
        super.reset()
        
        isHidden = false
    }
    
    public override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        
        guard let model = dashModel else { return }
        
        isHidden = model.isHidden
        dashColor = (model.inverted ? model.dashColor_inverted : model.dashColor).uiColor
        
        if let backgroundColor = model.backgroundColor {
            dashLayer?.backgroundColor = backgroundColor.uiColor.cgColor
        }
    }
}
