import UIKit
import Eureka
import PKHUD

class OsagoController: FormViewController {
    
    var vehicle: Vehicle? {
        didSet {
            self.updateInterface()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("OSAGO contracts", comment: "")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(checkNewDate(_:)))
        
        self.tableView.rowHeight = UITableView.automaticDimension
    }
    
    @objc func checkNewDate(_ sender: UIBarButtonItem) {
        guard let vehicle = self.vehicle else { return }
        
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let controller = sb.instantiateViewController(identifier: "OsagoAddController") as OsagoAddController
        controller.checkSources = [.plateNumber(number: vehicle.getNumber())]
        if let vin = vehicle.vin1, !vin.contains("*") {
            controller.checkSources.append(.vin(number: vin))
        }
        
        controller.onDone = { vehicle in
            self.navigationController?.popViewController(animated: true, completion: {
                self.update(vehicle: vehicle)
            })
        }
        
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    func updateInterface() {
        guard let vehicle = self.vehicle else { return }
        
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        
        self.form.removeAll()
        for osago in vehicle.osagoContracts.sorted(by: { $0.date < $1.date }) {
            self.form +++ Section(formatter.string(from: Date(timeIntervalSince1970: osago.date)))
                <<< self.multilineRow(NSLocalizedString("Contract series and number", comment: ""), value: osago.number)
                <<< self.multilineRow(NSLocalizedString("Insurance organization name", comment: ""), value: osago.name)
                <<< self.multilineRow(NSLocalizedString("OSAGO contract status", comment: ""), value: osago.status)
                <<< self.multilineRow(NSLocalizedString("Insurant", comment: ""), value: osago.insurant)
                <<< self.multilineRow(NSLocalizedString("Owner", comment: ""), value: osago.owner)
                <<< self.multilineRow(NSLocalizedString("Vehicle usage region", comment: ""), value: osago.usageRegion)
                <<< self.multilineRow(NSLocalizedString("Contract restrictions", comment: ""), value: osago.restrictions)
                <<< self.row(NSLocalizedString("Plate number", comment: ""), value: osago.plateNumber)
                <<< self.row(NSLocalizedString("VIN", comment: ""), value: osago.vin)
        }
    }
    
    func row(_ title: String, value: String?) -> LabelRow {
        LabelRow() { row in
            if let cell = row.cell, let label = cell.detailTextLabel, let titleLabel = cell.textLabel {
                titleLabel.translatesAutoresizingMaskIntoConstraints = false
                titleLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 8).isActive = true
                titleLabel.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor).isActive = true
                
                label.translatesAutoresizingMaskIntoConstraints = false
                label.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 8).isActive = true
                label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -8).isActive = true
                label.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 8).isActive = true
                label.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor).isActive = true
                label.numberOfLines = 0
                label.font = UIFont.preferredFont(forTextStyle: .subheadline)
            }

            row.title = title
            row.value = value
        }
    }
    
    func multilineRow(_ title: String, value: String?) -> MultilineLabelRow {
        MultilineLabelRow() { row in
            row.title = title
            row.value = value
        }
    }
    
    func update(vehicle: Vehicle) {
        do {
            if let realm = self.vehicle?.realm {
                try realm.write {
                    realm.add(vehicle, update: .all)
                }
            } else {
                self.vehicle?.osagoContracts.removeAll()
                self.vehicle?.osagoContracts.append(objectsIn: vehicle.osagoContracts)
            }
            self.updateInterface()
        } catch {
            HUD.show(error: error)
            print(error)
        }
    }
}
