//
//  PollOptionCheckboxView.swift
//  Tusker
//
//  Created by Shadowfacts on 4/25/21.
//  Copyright © 2021 Shadowfacts. All rights reserved.
//

import UIKit

class PollOptionCheckboxView: UIView {
    
    private static let size: CGFloat = 20

    var isChecked: Bool = false {
        didSet {
            updateStyle()
        }
    }
    var readOnly: Bool = true {
        didSet {
            updateStyle()
        }
    }
    var voted: Bool = false {
        didSet {
            updateStyle()
        }
    }
    var multiple: Bool = false {
        didSet {
            updateStyle()
        }
    }
    
    private let imageView: UIImageView
    
    init() {
        imageView = UIImageView(image: UIImage(systemName: "checkmark")!)
        
        super.init(frame: .zero)
        
        layer.cornerCurve = .continuous
        layer.borderWidth = 2
        
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isHidden = true
        addSubview(imageView)
        
        updateStyle()
        
        NSLayoutConstraint.activate([
            widthAnchor.constraint(equalTo: heightAnchor),
            widthAnchor.constraint(equalToConstant: PollOptionCheckboxView.size),
            
            imageView.widthAnchor.constraint(equalTo: widthAnchor, constant: -3),
            imageView.heightAnchor.constraint(equalTo: heightAnchor, constant: -3),
            imageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var intrinsicContentSize: CGSize {
        CGSize(width: 20, height: 20)
    }
    
    private func updateStyle() {
        layer.cornerRadius = (multiple ? 0.1 : 0.5) * PollOptionCheckboxView.size
        
        imageView.isHidden = !isChecked
        if voted || readOnly {
            layer.borderColor = UIColor.clear.cgColor
        } else if isChecked {
            layer.borderColor = tintColor.cgColor
        } else {
            layer.borderColor = UIColor.gray.cgColor
        }
        backgroundColor = isChecked && !voted ? tintColor : .clear
        imageView.tintColor = voted ? .label : .white
    }

}
