//
//  TubeTableViewController.swift
//  TubeList
//
//  Created by Виктор on 13.08.2019.
//  Copyright © 2019 SwiftViktor. All rights reserved.
//

import UIKit

class TubeTableViewController: UITableViewController {
    
    // MARK: - Properties
    var tubes = [Tube]()
    //FIXME: - real data
    let tubeInfoDate = TubeInfoDate(dayOfPurchase: Date(), dayOfManufactureOfTheTube: Date(), dayStartedUsingTube: Date())
    
    //MARK: - UITableViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.prefersLargeTitles = true
        //FIXME: - real tube info
        tubes = [
            Tube(tubeName: "300B", image: UIImage(named: "300B")!, company: "Electro Harmonix", favourite: false, tubeInfoDate: tubeInfoDate, tubeSpecifications: nil),
            Tube(tubeName: "KT88", image: UIImage(named: "KT88")!, company: "Svetlana", favourite: false, tubeInfoDate: tubeInfoDate, tubeSpecifications: nil),
            Tube(tubeName: "2A3", company: "Tung-Sol", favourite: true, tubeInfoDate: tubeInfoDate, tubeSpecifications: nil)
        ]
    }
    
    //MARK: - UITableViewCustomMethods
    private func configureCell(_ cell: MainTubeCell, from tube: Tube) {
        guard let stackView = cell.stackView else { return }
        guard let imageView = cell.tubeImageView else { return }
        guard stackView.arrangedSubviews.count == 0 else { return }
        
        for index in 0..<tube.keys.count {
            let key = tube.capitalizedKeys[index]
            let value = tube.values[index]
            if let stringValue = value as? String {
                let label = UILabel()
                label.text = "\(key): \(stringValue)"
                stackView.addArrangedSubview(label)
            } else if let imageValue = value as? UIImage {
                imageView.image = imageValue
            } else if let favouriteValue = value as? Bool {
                if favouriteValue {
                    let label = UILabel()
                    label.text = "\(key): \(favouriteValue ? "❤️" : "")"
                    stackView.addArrangedSubview(label)
                }
            }  else if let dateValue = value as? TubeInfoDate {
                guard let dayOfManufactureOfTheTube = dateValue.dayOfManufactureOfTheTube else { return }
                let label = UILabel()
                label.text = "Year of manufacture: \(dayOfManufactureOfTheTube.formattedDate)"
                stackView.addArrangedSubview(label)
            }
        }
    }
    
    //MARK: - UITableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tubes.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainTubeCell", for: indexPath) as! MainTubeCell
        let tube = tubes[indexPath.row]
        configureCell(cell, from: tube)
        return cell
    }
    
    //MARK: - UITableViewDelegate
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            tubes.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }
        
        //MARK: - Navigation
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            guard segue.identifier == "FullTubeInfoSegue" else { return }
            guard let selectedIndex = tableView.indexPathForSelectedRow else { return }
            let destination = segue.destination as! TubeDetailTableViewController
            destination.tube = tubes[selectedIndex.row].copy() as! Tube
        }
        
        @IBAction func unwind(_ segue: UIStoryboardSegue) {
            guard segue.identifier == "SaveSegue" else { return }
            guard let selectedIndex = tableView.indexPathForSelectedRow else { return }
            
            let source = segue.source as! TubeDetailTableViewController
            tubes[selectedIndex.row] = source.tube
            
            //FIXME: - image reloading
            if let tubeCell = tableView.cellForRow(at: selectedIndex) as? MainTubeCell {
                if let stackView = tubeCell.stackView {
                    stackView.arrangedSubviews.forEach { subview in
                        stackView.removeArrangedSubview(subview)
                        subview.removeFromSuperview()
                    }
                }
            }
            tableView.reloadRows(at: [selectedIndex], with: .automatic)
        }
}



