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

import Foundation
import UIKit

class PopupSelectorChildViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    var itemSelectedCallback: ((AnyObject, AnyObject?) -> Void)?
    
    var dataSource: [INameable]!
    var dataSourceType: String = ""
    
    var parentItem: AnyObject!
    
    var searchActive : Bool = false
    var shouldBeSearchBarHidden: Bool = true
    var shouldBeAddButtonHidden: Bool = true
    
    var selectedParentId: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setDelegate()
        self.createNavigationItem()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLayoutSubviews() {
        setLayout()
    }
    
    func setLayout(){
        self.searchBar.isHidden = shouldBeSearchBarHidden
        if shouldBeSearchBarHidden {
            self.tableView.frame.origin = CGPoint.init(x: self.searchBar.frame.origin.x, y: self.searchBar.frame.origin.y)
            self.tableView.frame.size.height = CGFloat.init(self.tableView.frame.size.height + self.searchBar.frame.size.height)
        }
        else{
            self.tableView.frame.origin = CGPoint.init(x: self.view.frame.origin.x, y: self.searchBar.frame.origin.y + self.searchBar.frame.size.height)
        }
    }
    
    func setDelegate(){
        self.tableView.delegate = self
        self.searchBar.delegate = self
    }
    
    func createNavigationItem(){
        if !shouldBeAddButtonHidden{
            let addNewButton = UIBarButtonItem(image: UIImage.init(named: "add.png"), style: .plain, target: self, action: #selector(addNewObject(_:)))
            self.navigationItem.rightBarButtonItem = addNewButton
        }
    }
    
    @objc func dismissView(_ sender: Any){
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func addNewObject(_ sender: Any){
       if dataSourceType == "Color"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new color"), UIViewController: self, actionYes: { text in
                self.addNewObjectAsTextCallback(text: text!)
            }) {
                return
            }
        }
    }
    
    func addNewObjectAsTextCallback(text: String){
        self.dismiss(animated: true, completion: {
            if let itemSelectedCallback = self.itemSelectedCallback {
                let item = text
                self.parentItem = self.selectedParentId as AnyObject
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
        })
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell
        
        let item = Array(self.dataSource)[indexPath.row]
        cell.textLabel?.text = item.customName
        
        cell.textLabel?.textAlignment = .center
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if dataSourceType == "FrameProducer"{
            let frameProducerLine = dataSource[indexPath.row] as! WSFramesProducerLinesView
            
            State.LoadProductsView(producerId: frameProducerLine.parentId * (-1), producerLineId: frameProducerLine.keyId, productFamilyCode: "MNT", filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorSecondChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorSecondChildViewController") as! PopupSelectorSecondChildViewController)
                    popupSelectorSecondChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorSecondChildViewController.itemSelectedCallback = self.selectedSecondChildValue
                    popupSelectorSecondChildViewController.dataSource = result!
                    popupSelectorSecondChildViewController.dataSourceType = "WSProductsView"
                    popupSelectorSecondChildViewController.selectedParentId = frameProducerLine.parentId
                    popupSelectorSecondChildViewController.selectedChildId = frameProducerLine.keyId
                    popupSelectorSecondChildViewController.selectedFamilyCode = "MNT"
                    popupSelectorSecondChildViewController.title = Util.getString("Products")
                    popupSelectorSecondChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorSecondChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "LensProducer"{
            let lensProducerLine = dataSource[indexPath.row] as! WSLensProducerLinesView
            
            State.LoadProductsView(producerId: lensProducerLine.parentId * (-1), producerLineId: lensProducerLine.keyId, productFamilyCode: "LOF", filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorSecondChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorSecondChildViewController") as! PopupSelectorSecondChildViewController)
                    popupSelectorSecondChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorSecondChildViewController.itemSelectedCallback = self.selectedSecondChildValue
                    popupSelectorSecondChildViewController.dataSource = result!
                    popupSelectorSecondChildViewController.dataSourceType = "WSProductsView"
                    popupSelectorSecondChildViewController.selectedParentId = lensProducerLine.parentId
                    popupSelectorSecondChildViewController.selectedChildId = lensProducerLine.keyId
                    popupSelectorSecondChildViewController.selectedFamilyCode = "LOF"
                    popupSelectorSecondChildViewController.title = Util.getString("Products")
                    popupSelectorSecondChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorSecondChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "ServicesProducer"{
            let serviceProducer = dataSource[indexPath.row] as! WSTreatmentsProducerLinesView
            
            State.LoadServicesAndTreatmentsProductsView(producerId: serviceProducer.parentId * (-1), producerLineId: serviceProducer.keyId, productFamilyCode: ["SRV","TRT"], filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorSecondChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorSecondChildViewController") as! PopupSelectorSecondChildViewController)
                    popupSelectorSecondChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorSecondChildViewController.itemSelectedCallback = self.selectedSecondChildValue
                    popupSelectorSecondChildViewController.dataSource = result!
                    popupSelectorSecondChildViewController.dataSourceType = "WSProductsView"
                    popupSelectorSecondChildViewController.selectedParentId = serviceProducer.parentId
                    popupSelectorSecondChildViewController.selectedChildId = serviceProducer.keyId
                    popupSelectorSecondChildViewController.selectedFamilyCode = "ServicesAndTreatments"
                    popupSelectorSecondChildViewController.title = Util.getString("Products")
                    popupSelectorSecondChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorSecondChildViewController, animated: true)
                }
            })
        }
        else {
            if let itemSelectedCallback = self.itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                self.parentItem = self.selectedParentId as AnyObject
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            self.dismiss(animated: true, completion: nil)
        }
    }
        
    func selectedSecondChildValue(item: AnyObject, parentItem: AnyObject?){
        if let itemSelectedCallback = itemSelectedCallback {
            itemSelectedCallback(item as AnyObject, self.parentItem)
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.setShowsCancelButton(true, animated: true)
        self.searchActive = true
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.perform(#selector(filterDataSource(searchText:)), with: searchText, afterDelay: 2)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.endEditing(true)
        self.searchActive = true
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.text = ""
        self.searchBar.showsCancelButton = false
        self.searchBar.endEditing(true)
        self.searchActive = false
        filterDataSource(searchText: nil)
    }
    
    @objc func filterDataSource(searchText: String?){
        if dataSourceType == "ProducerLine" {
            print("will search in ProducerLine")
            State.loadProducerLines(producersId: selectedParentId, filterString: searchText, completionHandler: { result in
                if result {
                    self.dataSource = State.producerLine
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Subfamily"  {
            print("will search in Subfamily")
            State.loadProductSubfamilies(productFamilyId: selectedParentId, filterString: searchText, completionHandler: { result in
                if result {
                    self.dataSource = State.productSubfamily
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Color"  {
            print("will search in Color")
            State.loadColors(colorGroupId: selectedParentId, filterString: searchText, completionHandler: {  result in
                if result {
                    self.dataSource = State.color
                    self.tableView.reloadData()
                }
            })
        }
    }
}
