import UIKit
import Eureka

class OwnersController: FormViewController {
    
    public var owners: [VehicleOwnershipPeriod] = []
    
    private var formatter = DateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.rowHeight = UITableView.automaticDimension
        
        self.formatter.dateStyle = .long
        self.formatter.timeStyle = .none
        
        self.title = String.localizedStringWithFormat(NSLocalizedString("owners count", comment: ""), self.owners.count)
        
        for (index, owner) in self.owners.enumerated() {
            
            let fromDate = Date(timeIntervalSince1970: TimeInterval(owner.from/1000))
            let from = self.formatter.string(from: fromDate)
            var to = NSLocalizedString("now", comment: "")
            if owner.to > 0 {
                let toDate = Date(timeIntervalSince1970: TimeInterval(owner.to/1000))
                to = self.formatter.string(from: toDate)
            }
            
            let section = Section(header: from + " - " + to, footer: owner.lastOperation)
            form +++ section
                <<< LabelRow("Owner\(index)") { row in
                    row.title = NSLocalizedString("Owner type", comment: "")
                    row.value = NSLocalizedString(owner.ownerType, comment: "")
                }
            
            if let vehicleRegistrationRegion = owner.region {
                section <<< MultilineLabelRow("VehicleRegion\(index)") { row in
                    row.title = NSLocalizedString("Vehicle region", comment: "")
                    row.value = vehicleRegistrationRegion
                }
            }
            
            
            if let driverLocality = owner.locality {
                var dRegion = driverLocality
                if let driverRegion = owner.registrationRegion {
                    dRegion += " (\(driverRegion))"
                }
                section <<< MultilineLabelRow("DriverRegion\(index)") { row in
                    row.title = NSLocalizedString("Driver region", comment: "")
                    row.value = dRegion
                }
            }
            
            if let code = owner.code {
                section <<< MultilineLabelRow("Code\(index)") { row in
                    row.title = NSLocalizedString("ZIP (or OKTMO) code", comment: "")
                    row.value = code
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}
