//
//  EditProductAttributesViewController.swift
//  iPOS
//
//  Created by bbc on 14/06/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit

class EditProductAttributesTableViewController: UITableViewController, UITextFieldDelegate, UIPopoverPresentationControllerDelegate {
    
    @IBOutlet weak var tfSupplier: UITextField!
    @IBOutlet weak var tfSeason: UITextField!
    @IBOutlet weak var tfProductType: UITextField!
    @IBOutlet weak var tfProductGroup: UITextField!
    @IBOutlet weak var tfSeasonality: UITextField!
    @IBOutlet weak var tfLinkage: UITextField!
    @IBOutlet weak var tfUM: UITextField!
    @IBOutlet weak var tfMaterial: UITextField!
    @IBOutlet weak var tfTheme: UITextField!
    @IBOutlet weak var tfEvent: UITextField!
    @IBOutlet weak var tfCustomCode: UITextField!
    @IBOutlet weak var tfComposition: UITextField!
    @IBOutlet weak var tfOriginCountry: UITextField!
    @IBOutlet weak var tfSizeClass: UITextField!
    @IBOutlet weak var tfVat: UITextField!
    
    @IBOutlet weak var attribute0: UITextField!
    @IBOutlet weak var attribute1: UITextField!
    @IBOutlet weak var attribute2: UITextField!
    @IBOutlet weak var attribute3: UITextField!
    @IBOutlet weak var attribute4: UITextField!
    @IBOutlet weak var attribute5: UITextField!
    @IBOutlet weak var attribute6: UITextField!
    @IBOutlet weak var attribute7: UITextField!
    @IBOutlet weak var attribute8: UITextField!
    @IBOutlet weak var attribute9: UITextField!
    
    var product: CustomProduct!
    var delegate: IProductTabBarModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegateTextField()
        self.setTableViewStyle()
        self.setCaptions()
    }
    
    func setCaptions(){
        State.getCustomResource(name: "ProductAttribute0", category: "General", completionHandler: {value in
            self.attribute0.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute1", category: "General", completionHandler: {value in
            self.attribute1.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute2", category: "General", completionHandler: {value in
            self.attribute2.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute3", category: "General", completionHandler: {value in
            self.attribute3.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute4", category: "General", completionHandler: {value in
            self.attribute4.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute5", category: "General", completionHandler: {value in
            self.attribute5.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute6", category: "General", completionHandler: {value in
            self.attribute6.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute7", category: "General", completionHandler: {value in
            self.attribute7.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute8", category: "General", completionHandler: {value in
            self.attribute8.placeholder = value
        })
        State.getCustomResource(name: "ProductAttribute9", category: "General", completionHandler: {value in
            self.attribute9.placeholder = value
        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.initProduct()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    func setTableViewStyle(){
        self.tableView.separatorStyle = .none
    }
    
    func initProduct(){
        self.product = delegate.getCurrentProduct()
        if delegate.isNew() {
            
        }
        else{
            self.tfSupplier.text = self.product.supplierName
            self.tfSeason.text = self.product.seasonName
            self.tfProductType.text = self.product.productTypeName
            self.tfProductGroup.text = self.product.productGroupName
            self.tfSeasonality.text = self.product.seasonalityName
            self.tfLinkage.text = self.product.linkageName
            self.tfUM.text = self.product.unitOfMeasureName
            self.tfMaterial.text = self.product.materialName
            self.tfTheme.text = self.product.themeName
            self.tfEvent.text = self.product.eventName
            self.tfCustomCode.text = self.product.customCode
            self.tfComposition.text = self.product.compositionName
            self.tfOriginCountry.text = self.product.originCountryName
            
            self.attribute0.text = self.product.attribute0Name
            self.attribute1.text = self.product.attribute1Name
            self.attribute2.text = self.product.attribute2Name
            self.attribute3.text = self.product.attribute3Name
            self.attribute4.text = self.product.attribute4Name
            self.attribute5.text = self.product.attribute5Name
            self.attribute6.text = self.product.attribute6Name
            self.attribute7.text = self.product.attribute7Name
            self.attribute8.text = self.product.attribute8Name
            self.attribute9.text = self.product.attribute9Name
        }
        
        self.tfVat.text = product.vatName
        self.tfSizeClass.text = product.sizeClassName
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
    }

    func delegateTextField(){
        self.tfSupplier.delegate = self
        self.tfVat.delegate = self
        self.tfSizeClass.delegate = self
        self.tfSeason.delegate = self
        self.tfProductType.delegate = self
        self.tfProductGroup.delegate = self
        self.tfSeasonality.delegate = self
        self.tfLinkage.delegate = self
        self.tfUM.delegate = self
        self.tfMaterial.delegate = self
        self.tfTheme.delegate = self
        self.tfEvent.delegate = self
        self.tfCustomCode.delegate = self
        self.tfComposition.delegate = self
        self.tfOriginCountry.delegate = self
        
        self.attribute0.delegate = self
        self.attribute1.delegate = self
        self.attribute2.delegate = self
        self.attribute3.delegate = self
        self.attribute4.delegate = self
        self.attribute5.delegate = self
        self.attribute6.delegate = self
        self.attribute7.delegate = self
        self.attribute8.delegate = self
        self.attribute9.delegate = self
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if  textField == tfSupplier || textField == tfVat || textField == tfSizeClass || textField == tfSeason || textField == tfProductType || textField == tfProductGroup || textField == tfSeasonality || textField == tfLinkage || textField == tfUM || textField == tfOriginCountry || textField == tfMaterial || textField == tfTheme || textField == tfEvent || textField == tfCustomCode || textField == tfComposition || textField == attribute0 || textField == attribute1 || textField == attribute2 || textField == attribute3 || textField == attribute4 || textField == attribute5 || textField == attribute6 || textField == attribute7 || textField == attribute8 || textField == attribute9{
            textField.resignFirstResponder()
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.view.endEditing(true)
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == tfSizeClass {
            self.dismissKeyboard()
            State.loadSizeClasses(filterString: nil) { result in
                if result {
                    self.openPopUp(self.tfSizeClass, State.sizeClass, "SizeClass", Util.getString("Size Classes"))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            return false
        }
        else if textField == tfSupplier{
            self.dismissKeyboard()
            State.loadSuppliersFromCompanies(filterString: nil) { result in
                if let suppliers = result{
                    self.openPopUpWithParent(self.tfSupplier, suppliers, "Suppliers", Util.getString("Suppliers"), shouldBeSearchBarHidden: true, shouldBeAddButtonHidden: false)
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            return false
        }
        else if textField == tfVat{
            self.dismissKeyboard()
            State.loadVats(filterString: nil) { result in
                if result {
                    self.openPopUp(self.tfVat, State.vat, "Vat", Util.getString("Vats"))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            return false
        }
        else if textField == tfSeason {
            self.dismissKeyboard()
            State.loadSeason(filterString: nil) { result in
                if result {
                    self.openPopUp(self.tfSeason, State.seasons, "Season", Util.getString("Seasons"))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            return false
        }
        else if textField == tfProductType {
            
            return false
        }
        else if textField == tfProductGroup {
        
            return false
        }
        else if  textField == tfSeasonality{
            
            return false
        }
        else if  textField == tfLinkage{
            
            return false
        }
        else if  textField == tfUM{
            
            return false
        }
        else if  textField == tfOriginCountry{
            
            return false
        }
        else if  textField == tfMaterial{
            self.dismissKeyboard()
            State.loadMaterials { response in
                if let materials = response{
                    self.openPopUpWithParent(textField, materials, "Material", Util.getString("Materials"), shouldBeSearchBarHidden: true, shouldBeAddButtonHidden: false)
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            return false
        }
        else if  textField == tfTheme{
            
            return false
        }
        else if  textField == tfEvent{
            
            return false
        }
        else if  textField == tfCustomCode{
            
            return false
        }
        else if  textField == tfComposition{
            
            return false
        }
        else if textField == attribute0 {
            self.dismissKeyboard()
            State.loadProductAttribute0(completionHandler: { response in
                if let attribute0 = response{
                    self.openPopUp(textField, attribute0, "Product Attribute0", Util.getString(self.attribute0.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if textField == attribute1 {
            self.dismissKeyboard()
            State.loadProductAttribute1(completionHandler: { response in
                if let attribute1 = response{
                    self.openPopUp(textField, attribute1, "Product Attribute1", Util.getString(self.attribute1.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute2{
            self.dismissKeyboard()
            State.loadProductAttribute2(completionHandler: { response in
                if let attribute2 = response{
                    self.openPopUp(textField, attribute2, "Product Attribute2", Util.getString(self.attribute2.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute3{
            self.dismissKeyboard()
            State.loadProductAttribute3(completionHandler: { response in
                if let attribute3 = response{
                    self.openPopUp(textField, attribute3, "Product Attribute3", Util.getString(self.attribute3.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute4{
            self.dismissKeyboard()
            State.loadProductAttribute4(completionHandler: { response in
                if let attribute4 = response{
                    self.openPopUp(textField, attribute4, "Product Attribute4", Util.getString(self.attribute4.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute5{
            self.dismissKeyboard()
            State.loadProductAttribute5(completionHandler: { response in
                if let attribute5 = response{
                    self.openPopUp(textField, attribute5, "Product Attribute5", Util.getString(self.attribute5.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute6{
            self.dismissKeyboard()
            State.loadProductAttribute6(completionHandler: { response in
                if let attribute6 = response{
                    self.openPopUp(textField, attribute6, "Product Attribute6", Util.getString(self.attribute6.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute7{
            self.dismissKeyboard()
            State.loadProductAttribute7(completionHandler: { response in
                if let attribute7 = response{
                    self.openPopUp(textField, attribute7, "Product Attribute7", Util.getString(self.attribute7.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute8{
            self.dismissKeyboard()
            State.loadProductAttribute8(completionHandler: { response in
                if let attribute8 = response{
                    self.openPopUp(textField, attribute8, "Product Attribute8", Util.getString(self.attribute8.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        else if  textField == attribute9{
            self.dismissKeyboard()
            State.loadProductAttribute9(completionHandler: { response in
                if let attribute9 = response{
                    self.openPopUp(textField, attribute9, "Product Attribute9", Util.getString(self.attribute9.placeholder!))
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
            return false
        }
        return true
    }
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .fullScreen
    }
    
    func openPopUpWithParent(_ textField: UITextField, _ dataSource: [INameable], _ dataSourceType: String, _ title: String, shouldBeSearchBarHidden: Bool, shouldBeAddButtonHidden: Bool) {
        let popupSelectorViewController = self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.shouldBeSearchBarHidden = shouldBeSearchBarHidden
        popupSelectorViewController.shouldBeAddButtonHidden = shouldBeAddButtonHidden
        popupSelectorViewController.itemSelectedCallback = selectedValue
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.dataSourceType = dataSourceType
        popupSelectorViewController.title = title
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    func openPopUp(_ textField: UITextField, _ dataSource: [INameable], _ dataSourceType: String, _ title: String ) {
        let popupSelectorViewController = self.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
        let popover = nav.popoverPresentationController
        popover?.permittedArrowDirections = .up
        popupSelectorViewController.preferredContentSize = CGSize(width: textField.frame.size.width, height: 300)
        popover?.delegate = self
        popover?.sourceView = textField
        popover?.sourceRect = CGRect(x: textField.frame.size.width/2.0, y: textField.frame.size.height, width: 0, height: 0)
        self.present(nav, animated: true, completion: nil)
    }
    
    func selectedValue(item: AnyObject, parentItem: AnyObject?){
        if item.isKind(of: SizeClass.self){
            let sizeClass = item as! SizeClass
            self.tfSizeClass.text = sizeClass.name
            product.sizeClassName = sizeClass.name
            product.sizeClassId = sizeClass.sizeClassId
        }
        else if item.isKind(of: Company.self){
            let company = item as! Company
            self.product.supplierId = company.companyId
            self.product.supplierName = company.name
            self.tfSupplier.text = company.name
        }
        else if item.isKind(of: Vat.self){
            let vat = item as! Vat
            self.tfVat.text = vat.name
            product.vatName = vat.name
            product.vatCode = vat.code
        }
        else if item.isKind(of: Season.self){
            let season = item as! Season
            self.tfSeason.text = season.name
            
            product.seasonId = season.seasonId
            product.seasonName = season.name
        }
        else if item.isKind(of: ProductAttribute0.self){
            let attribute0 = item as! ProductAttribute0
            self.product.attribute0Id = attribute0.id
            self.product.attribute0Name = attribute0.name
            self.product.attribute0Code = attribute0.code
            self.attribute0.text = attribute0.name
        }
        else if item.isKind(of: ProductAttribute1.self){
            let attribute1 = item as! ProductAttribute1
            self.product.attribute1Id = attribute1.id
            self.product.attribute1Name = attribute1.name
            self.product.attribute1Code = attribute1.code
            self.attribute1.text = attribute1.name
        }
        else if item.isKind(of: ProductAttribute2.self){
            let attribute2 = item as! ProductAttribute2
            self.product.attribute2Id = attribute2.id
            self.product.attribute2Name = attribute2.name
            self.product.attribute2Code = attribute2.code
            self.attribute2.text = attribute2.name
        }
        else if item.isKind(of: ProductAttribute3.self){
            let attribute3 = item as! ProductAttribute3
            self.product.attribute3Id = attribute3.id
            self.product.attribute3Name = attribute3.name
            self.product.attribute3Code = attribute3.code
            self.attribute3.text = attribute3.name
        }
        else if item.isKind(of: ProductAttribute4.self){
            let attribute4 = item as! ProductAttribute4
            self.product.attribute4Id = attribute4.id
            self.product.attribute4Name = attribute4.name
            self.product.attribute4Code = attribute4.code
            self.attribute4.text = attribute4.name
        }
        else if item.isKind(of: ProductAttribute5.self){
            let attribute5 = item as! ProductAttribute5
            self.product.attribute5Id = attribute5.id
            self.product.attribute5Name = attribute5.name
            self.product.attribute5Code = attribute5.code
            self.attribute5.text = attribute5.name
        }
        else if item.isKind(of: ProductAttribute6.self){
            let attribute6 = item as! ProductAttribute6
            self.product.attribute6Id = attribute6.id
            self.product.attribute6Name = attribute6.name
            self.product.attribute6Code = attribute6.code
            self.attribute6.text = attribute6.name
        }
        else if item.isKind(of: ProductAttribute7.self){
            let attribute7 = item as! ProductAttribute7
            self.product.attribute7Id = attribute7.id
            self.product.attribute7Name = attribute7.name
            self.product.attribute7Code = attribute7.code
            self.attribute7.text = attribute7.name
        }
        else if item.isKind(of: ProductAttribute8.self){
            let attribute8 = item as! ProductAttribute8
            self.product.attribute8Id = attribute8.id
            self.product.attribute8Name = attribute8.name
            self.product.attribute8Code = attribute8.code
            self.attribute8.text = attribute8.name
        }
        else if item.isKind(of: ProductAttribute9.self){
            let attribute9 = item as! ProductAttribute9
            self.product.attribute9Id = attribute9.id
            self.product.attribute9Name = attribute9.name
            self.product.attribute9Code = attribute9.code
            self.attribute9.text = attribute9.name
        }
        else if item.isKind(of: Material.self){
            let material = item as! Material
            self.tfMaterial.text = material.name
            
            product.materialId = material.materialId
            product.materialName = material.name
        }
        else if item is String{
            if let parentItem = parentItem{
                if parentItem.isEqual(Material.self){
                    product.materialId = nil
                    product.materialName = item as? String
                    
                    self.tfMaterial.text = item as? String
                }
                else if parentItem.isEqual(Company.self){
                    product.supplierId = nil
                    product.supplierName = item as? String
                    
                    self.tfSupplier.text = item as? String
                }
            }
        }
        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)
        }
        
        customLabel.text = Util.getString(self.tableView(tableView, titleForHeaderInSection: section)!)
        customLabel.textColor = UIColor.white
        customLabel.textAlignment = .center
        return customLabel
    }
}
