//
//  EditProductFeaturesTableViewController.swift
//  iPOS
//
//  Created by Zoran Albu on 1/25/18.
//  Copyright © 2018 BBC. All rights reserved.
//

import Foundation
import UIKit

protocol IProductFeatures {
    func addFeatureValue(feature: Features, featureValue: FeatureValues)
}

class EditProductFeaturesTableViewController: UITableViewController, IProductFeatures {
    
    var product: CustomProduct!
    var delegate: IProductTabBarModel!
    var numberOfRowsInSection: Int = 0
    var lastFamilyId: Int? = -1
    var lastSubfamilyId: Int? = -1
    
    var features: [Features] = [Features]()
    var featureValues: [FeatureValues] = [FeatureValues]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setTableViewStyle()
        self.loadProductFeatures()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.initProduct()
        self.loadFeatures()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    func setTableViewStyle(){
        self.tableView.allowsSelection = false
        self.tableView.separatorStyle = .none
    }
    
    func initProduct(){
        self.product = delegate.getCurrentProduct()
    }
    
    func loadProductFeatures(){
        self.initProduct()
        if let productId = self.product.productId{
            State.loadFeaturesForProduct(productId: productId, completionHandler: { result in
                if let featuresForProduct = result{
                    self.product.featuresForProduct = featuresForProduct
                    self.tableView.reloadData()
                }
            })
        }
    }
    
    func loadFeatures(){
        if self.product.productFamilyId == self.lastFamilyId && self.product.productSubfamilyId == self.lastSubfamilyId{
            return
        }
        
        self.lastFamilyId = self.product.productFamilyId
        self.lastSubfamilyId = self.product.productSubfamilyId
        self.product.featuresForProduct = [FeaturesForProduct]()
        
        State.loadFeatures(familyId: product.productFamilyId, subfamilyId: product.productSubfamilyId) { result in
            if let features = result {
                self.features = features
                self.numberOfRowsInSection = features.count
               
                self.tableView.reloadData()
            }
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.numberOfRowsInSection
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! FeaturesCustomCell
        
        let feature = self.features[indexPath.row]
        let featuresForProduct = self.findFeatureValue(feature: feature)
        
        cell.tfCustomText.text = featuresForProduct.featureValue
        cell.feature = feature
        cell.featuresForProduct = featuresForProduct
        cell.delegate = self
        
        return cell
    }
    
    func findFeatureValue(feature: Features) -> FeaturesForProduct{
        var featuresForProduct = FeaturesForProduct()
        for value in self.product.featuresForProduct{
            if value.featureId == feature.featureId{
                featuresForProduct = value
                break
            }
        }
        return featuresForProduct
    }
    
    func addFeatureValue(feature: Features,featureValue: FeatureValues) {
        var alreadyExist: Bool = false
        for featureForProduct in self.product.featuresForProduct{
            if featureForProduct.featureId == featureValue.featureId{
                featureForProduct.featureValueId = featureValue.featureValueId
                featureForProduct.featureValue = featureValue.value
                alreadyExist = true
                break
            }
        }
        if alreadyExist == false{
            let featureForProduct: FeaturesForProduct = FeaturesForProduct()
            
            featureForProduct.productId = self.product.productId
            featureForProduct.featureId = feature.featureId
            featureForProduct.featureName = feature.name
            featureForProduct.featureValueId = featureValue.featureValueId
            featureForProduct.featureValue = featureValue.value
           
            self.product.featuresForProduct.append(featureForProduct)
        }
        delegate.setSaveButtonStatus(isEnabled: true)
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 25
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let customLabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: tableView.bounds.height))
        
        if section % 2 == 0{
            customLabel.backgroundColor = UIColor.init(red: 0.500, green: 0.0, blue: 0.500, alpha: 1.0)
        }
        else{
            customLabel.backgroundColor = UIColor.init(red: 0.0, green: 0.500, blue: 0.100, alpha: 1.0)
        }
        
        if let familyName = self.product.productFamilyName{
            customLabel.text = familyName
            if let subfamilyName = self.product.productSubfamilyName{
                customLabel.text?.append(" - " + subfamilyName)
            }
            
            customLabel.textColor = UIColor.white
            customLabel.textAlignment = .center
        }
        return customLabel
    }
}

class FeaturesCustomCell: UITableViewCell, UITextFieldDelegate, UIPopoverPresentationControllerDelegate {
 
    @IBOutlet weak var tfCustomText: UITextField!
    
    var feature: Features!
    var featuresForProduct: FeaturesForProduct?
    
    var delegate: IProductFeatures!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.tfCustomText.delegate = self
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.addRightView()
    }
    
    func addRightView(){
        let height = tfCustomText.frame.height
        let size: CGSize = feature.name.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)])
        
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: height))
        label.textAlignment = NSTextAlignment.right
        label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
        label.text = feature.name
        tfCustomText.rightView = label
        tfCustomText.rightViewMode = .unlessEditing
        tfCustomText.text = self.featuresForProduct?.featureValue
    }
    
    func dismissKeyboard() {
        self.endEditing(true)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.dismissKeyboard()
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == tfCustomText {
            textField.resignFirstResponder()
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == tfCustomText{
            self.dismissKeyboard()
            State.loadFeatureValues(featureId: self.feature.featureId) { result in
                if let featureValues =  result{
                    self.openPopUp(featureValues, "Feature Values", self.feature.name! )
                }
            }
            return false
        }
        return true
    }
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .fullScreen
    }
    
    func openPopUp(_ dataSource: [INameable], _ dataSourceType: String, _ title: String ) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let popupSelectorViewController = storyboard.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.shouldBeSearchBarHidden = false
        popupSelectorViewController.itemSelectedCallback = selectedValue
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.dataSourceType = dataSourceType
        popupSelectorViewController.title = title
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.window?.rootViewController?.present(nav, animated: true, completion: nil)
    }
    
    func selectedValue(item: AnyObject, parentItem: AnyObject?){
        if item.isKind(of: FeatureValues.self){
            let featureValue = item as! FeatureValues
            tfCustomText.text = featureValue.value
            self.featuresForProduct?.featureValue = featureValue.value
            delegate.addFeatureValue(feature: self.feature, featureValue: featureValue)
        }
    }
}
