import UIKit
import Eureka

extension DebugInfoStatus {
    var color: UIColor {
        switch self {
        case .success: return .systemGreen
        case .error: return .systemRed
        case .warning: return .systemOrange
        }
    }
}

class SourceStatusCell: Cell<DebugInfoEntry>, CellType {
    private var circle: UIImageView!
    
    required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func setup() {
        super.setup()
        
        self.selectionStyle = .none
        
        self.circle = UIImageView(frame: .zero)
        self.circle.translatesAutoresizingMaskIntoConstraints = false
        self.circle.image = UIImage(systemName: "circle.fill")
        self.contentView.addSubview(self.circle)
        NSLayoutConstraint.activate([
            self.circle.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
            self.circle.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor)
        ])
    }
    
    override func update() {
        super.update()
        
        self.detailTextLabel?.text = nil
        if let value = row.value {
            self.circle.tintColor = value.statusEnum.color
            //self.accessoryType = value.error == nil ? .none : .disclosureIndicator
        } else {
            self.circle.tintColor = .systemGray
            //self.accessoryType = .none
        }
    }
}

final class SourceStatusRow: Row<SourceStatusCell>, RowType {
    required init(tag: String?) {
        super.init(tag: tag)
        cellProvider = CellProvider<SourceStatusCell>()
        self.onCellSelection { cell, row in
            if let error = row.value?.error, let controller = cell.parentViewController {
                let alert = UIAlertController(title: row.title, message: error, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                controller.present(alert, animated: true)
            }
        }
    }
}
