//
//  PopupSelectorViewController.swift
//  iPOS
//
//  Created by bbc on 12/01/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit


class PopupSelectorViewController: 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 dataSourceURL: String = ""
    
    var parentItem: AnyObject!
    
    var searchActive : Bool = false
    var shouldBeSearchBarHidden: Bool = true
    var shouldBeAddButtonHidden: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setDelegate()
        self.createNavigationItems()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func setDelegate(){
        self.tableView.delegate = self
        self.searchBar.delegate = self
    }
    
    func createNavigationItems(){
        let dismissButton = UIBarButtonItem(image: UIImage.init(named: "cancelButton.png"), style: .plain, target: self, action: #selector(dismissView(_:)))
        self.navigationItem.leftBarButtonItem = dismissButton
        
        if !shouldBeAddButtonHidden{
            let addNewButton = UIBarButtonItem(image: UIImage.init(named: "add.png"), style: .plain, target: self, action: #selector(addNewObject(_:)))
            self.navigationItem.rightBarButtonItem = addNewButton
        }
    }
    
    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)
        }
    }
    
    @objc func dismissView(_ sender: Any){
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func addNewObject(_ sender: Any){
        if dataSourceType == "Supplier"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new supplier"), UIViewController: self, actionYes: { text in
                self.parentItem = Company.self
                self.addNewObjectAsTextCallback(text: text!)
            }) {
                return
            }
        }
        else if dataSourceType == "Material"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new type of material"), UIViewController: self, actionYes: { text in
                self.parentItem = Material.self
                self.addNewObjectAsTextCallback(text: text!)
            }) {
                return
            }
        }
        else 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
            }
        }
        else if dataSourceType == "Prescriber"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new prescriber"), UIViewController: self, actionYes: { text in
                self.addNewObjectAsTextCallback(text: text!)
            }) {
                return
            }
        }
        else if dataSourceType == "SecuritySystemUser_OP"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new user"), UIViewController: self, actionYes: { text in
                self.addNewObjectAsTextCallback(text: text!)
            }) {
                return
            }
        }
        else if dataSourceType == "SecuritySystemUser_OM"{
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("Insert the name of a new user"), 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
                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 == "Producer"{
            let producer = dataSource[indexPath.row] as! Producer
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadProducerLines(producersId: producer.producerId, filterString: nil, completionHandler: { result in
                if result {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = State.producerLine
                    popupSelectorChildViewController.dataSourceType = "ProducerLine"
                    popupSelectorChildViewController.selectedParentId = producer.producerId
                    popupSelectorChildViewController.title = Util.getString("Lines")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "Family"{
            let family = dataSource[indexPath.row] as! ProductFamily
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadProductSubfamilies(productFamilyId: family.productFamilyId, filterString: nil, completionHandler: { result in
                if result {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = State.productSubfamily
                    popupSelectorChildViewController.dataSourceType = "Subfamily"
                    popupSelectorChildViewController.selectedParentId = family.productFamilyId
                    popupSelectorChildViewController.title = Util.getString("Subfamilies")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "ColorGroup"{
            let colorGroup = dataSource[indexPath.row] as! ColorGroup
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadColors(colorGroupId: colorGroup.colorGroupId, filterString: nil, completionHandler: { result in
                if result {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = false
                    popupSelectorChildViewController.shouldBeAddButtonHidden = false
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = State.color
                    popupSelectorChildViewController.dataSourceType = "Color"
                    popupSelectorChildViewController.selectedParentId = colorGroup.colorGroupId
                    popupSelectorChildViewController.title = Util.getString("Colors")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "FrameProducer"{
            let frameProducer = dataSource[indexPath.row] as! WSFramesProducerLinesView
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadFramesProducerLinesView(parentId: frameProducer.keyId, filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = true
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = result!
                    popupSelectorChildViewController.dataSourceType = self.dataSourceType
                    popupSelectorChildViewController.selectedParentId = frameProducer.parentId
                    popupSelectorChildViewController.title = Util.getString("Lines")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "LensProducer"{
            let lensProducer = dataSource[indexPath.row] as! WSLensProducerLinesView
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadLensProducerLinesView(parentId: lensProducer.keyId, filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = true
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = result!
                    popupSelectorChildViewController.dataSourceType = self.dataSourceType
                    popupSelectorChildViewController.selectedParentId = lensProducer.parentId
                    popupSelectorChildViewController.title = Util.getString("Lines")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "ServicesProducer"{
            let servicesProducer = dataSource[indexPath.row] as! WSTreatmentsProducerLinesView
            
            if let itemSelectedCallback = itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            
            State.loadServicesProducerLinesView(parentId: servicesProducer.keyId, filterString: nil, completionHandler: { result in
                if result != nil {
                    let popupSelectorChildViewController = (self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorChildViewController") as! PopupSelectorChildViewController)
                    popupSelectorChildViewController.shouldBeSearchBarHidden = true
                    popupSelectorChildViewController.itemSelectedCallback = self.selectedChildValue
                    popupSelectorChildViewController.dataSource = result!
                    popupSelectorChildViewController.dataSourceType = self.dataSourceType
                    popupSelectorChildViewController.selectedParentId = servicesProducer.parentId
                    popupSelectorChildViewController.title = Util.getString("Lines")
                    popupSelectorChildViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(popupSelectorChildViewController, animated: true)
                }
            })
        }
        else if dataSourceType == "DiscountCauses"{
            if let itemSelectedCallback = self.itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                self.dismiss(animated: true, completion: {
                    itemSelectedCallback(item as AnyObject, self.parentItem)
                })
            }
        }
        else{
            if let itemSelectedCallback = self.itemSelectedCallback {
                let item = self.dataSource[indexPath.row]
                itemSelectedCallback(item as AnyObject, self.parentItem)
            }
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    func selectedChildValue(item: AnyObject, parentItem: AnyObject?){
        if let itemSelectedCallback = itemSelectedCallback {
            itemSelectedCallback(item as AnyObject, 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 == "Season" {
            print("will search in seasons")
            State.loadSeason(filterString: searchText) { result in
                if result {
                    self.dataSource = State.seasons
                    self.tableView.reloadData()
                }
            }
        }
        else if dataSourceType == "SizeClass"  {
            print("will search in size classes")
            State.loadSizeClasses(filterString: searchText) { result in
                if result {
                    self.dataSource = State.sizeClass
                    self.tableView.reloadData()
                }
            }
        }
        else if dataSourceType == "Vat"  {
            print("will search in vats")
            State.loadVats(filterString: searchText) { result in
                if result {
                    self.dataSource = State.vat
                    self.tableView.reloadData()
                }
            }
        }
        else if dataSourceType == "Producer" {
            print("will search in Producer")
            State.LoadProducersWithoutFilters(filterString: searchText, completionHandler: { result in
                if result {
                    self.dataSource = State.producer
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Family"  {
            print("will search in size Family")
            State.loadProductFamilies(filterString: searchText, completionHandler: { result in
                if result {
                    self.dataSource = State.productFamily
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Cities"  {
            print("will search in size Cities")
            if searchText != nil && searchText != "" {
                State.loadCities(filterString: searchText, completionHandler: { result in
                    if result {
                        self.dataSource = State.cities
                        self.tableView.reloadData()
                    }
                })
            }
        }
        else if dataSourceType == "FrameProducer"{
            print("will search in size Producers -> Frame")
            State.loadFramesProducerLinesView(parentId: 0, filterString: searchText, completionHandler: {  result in
                if result != nil {
                    self.dataSource = result!
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "LensProducer"  {
            print("will search in size Producers -> Lens")
            State.loadLensProducerLinesView(parentId: 0, filterString: searchText, completionHandler: {  result in
                if result != nil {
                    self.dataSource = result!
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "ServicesProducer"  {
            print("will search in size Producers -> Services")
            State.loadServicesProducerLinesView(parentId: 0, filterString: searchText, completionHandler: {  result in
                if result != nil {
                    self.dataSource = result!
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Supplier"  {
            print("will search in size Supplier from Companies")
            State.loadSuppliersFromCompanies(filterString: searchText, completionHandler: { result in
                if result != nil {
                    self.dataSource = result!
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Color"  {
            print("will search in Color")
            State.loadColors(colorGroupId: self.parentItem as! Int, filterString: searchText, completionHandler: {  result in
                if result {
                    self.dataSource = State.color
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Prescriber"{
            State.loadPrescribers(filterString: searchText, completionHandler: { result in
                if let prescribers = result{
                    self.dataSource = prescribers
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "Store" {
            print("will search in stores")
            State.loadStores(dataSource: self.dataSourceURL, searchText) { result in
                if result {
                    self.dataSource = State.stores
                    self.tableView.reloadData()
                }
            }
        }
        else if dataSourceType == "SecuritySystemUser_OP"{
            State.loadUserAndRole(filterString: searchText, completionHandler: { result in
                if let users = result{
                    self.dataSource = users.filter({ $0.roleCode == "OP" })
                    self.tableView.reloadData()
                }
            })
        }
        else if dataSourceType == "SecuritySystemUser_OM"{
            State.loadUserAndRole(filterString: searchText, completionHandler: { result in
                if let users = result{
                    self.dataSource = users.filter({ $0.roleCode == "OM" })
                    self.tableView.reloadData()
                }
            })
        }
    }
}
