//
//  Slider.swift
//  VDSSample
//
//  Created by Matt Bruce on 6/15/23.
//

import Foundation
import UIKit
import VDS

class Slider: Control, UITextFieldDelegate {
    var textField = NumericField().with { $0.translatesAutoresizingMaskIntoConstraints = false }
    var range = UISlider().with { $0.translatesAutoresizingMaskIntoConstraints = false }
    var maximumValue: Float = 0.0  { didSet { range.maximumValue = maximumValue }}
    var minimumValue: Float = 0.0 { didSet { range.minimumValue = minimumValue }}
    var value: Float = 0.0 { didSet { range.value = value; setNeedsUpdate() }}
    override func setup() {
        addSubview(textField)
        addSubview(range)
        textField.delegate = self
        textField.pinTop()
        textField.pinBottom()
        textField.pinLeading()
        textField.heightAnchor.constraint(equalToConstant: 44).isActive = true
        textField.widthAnchor.constraint(equalToConstant: 75).isActive = true
        textField.pinTrailing(range.leadingAnchor, 10)
        range.pinTop()
        range.pinBottom()
        range.pinTrailing()
        
        range.thumbTintColor = .systemBlue
        range.publisher(for: .valueChanged).sink { [weak self] slider in
            self?.valueChanged(newValue: slider.value)
        }.store(in: &subscribers)
    }
    
    override func updateView() {
        textField.text = String(format: "%.2f", value)
    }
    
    private func valueChanged(newValue: Float) {
        value = newValue
        sendActions(for: .valueChanged)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if let text = textField.text, let n = NumberFormatter().number(from: text) {
            valueChanged(newValue: n.floatValue)
        }
        return true
    }
}
