//
//  ProductViewController.swift
//  iPOS
//
//  Created by bbc on 25/11/16.
//  Copyright © 2016 BBC. All rights reserved.
//

import UIKit

class ProductViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate, UIPopoverPresentationControllerDelegate, ProductFiltersViewControllerDelegate, UIGestureRecognizerDelegate {
 
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var btSortButton: UIButton!
    @IBOutlet weak var btFilterProducts: UIButton!
    @IBOutlet weak var lfFilter: UILabel!
    @IBOutlet weak var lfSort: UILabel!
    @IBOutlet weak var lfNumberOfProducts: UILabel!
    @IBOutlet weak var svProductEvents: UIStackView!
    @IBOutlet weak var svFilter: UIStackView!
    @IBOutlet weak var svSort: UIStackView!
    @IBOutlet weak var svNumberOfProducts: UIStackView!
    @IBOutlet weak var viewFilter: UIView!
    @IBOutlet weak var viewSort: UIView!
    @IBOutlet weak var viewCount: UIView!
    
    var delegate: IProductSelectorListener!
    var lastRequestReturnData = true
    var searchActive: Bool = false
    
    //Filter
    var totalFiltersCount = 0
    
    var filterString: String?
    var sortTypeString: String = ""
    
    var availableFilters: [IFilters] = []
    var availableDetailFilters: [IFilters] = []
    
    var selectedFamilyIds: [Int] = [Int]()
    var selectedFamilyCodes: [String] = [String]()
    var selectedSubfamilyIds: [Int] = [Int]()
    var selectedSubfamilyCodes: [String] = [String]()
    
    var selectedProducerIds: [Int] = [Int]()
    var selectedProducerLineIds: [Int] = [Int]()
    
    var selectedFeatureIds: [Int] = [Int]()
    var selectedFeatureValueIds: [Int] = [Int]()
    var criteriaXPO: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.searchBar.delegate = self

        if let title = self.title{
            self.searchBar.placeholder = Util.getString("Search") + " \(title)"
        }
        
        if(self.filterString != nil && self.filterString != ""){
            self.searchBar.text = self.filterString
        }
 
        self.createTopButtonsInsets()
        self.setCustomLayout()
        
        self.loadProductsView(top: 100, skip: 0, filterString: self.filterString, shouldLoadFilters: true)
        
        if settings.storeSetupSettings.isEditingProductsEnabled{
            self.longGesture()
        }
    }
    
    func setCustomLayout(){
        self.viewFilter.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewFilter.layer.borderWidth = 1
        self.viewFilter.layer.cornerRadius = 10
        
        self.viewSort.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewSort.layer.borderWidth = 1
        self.viewSort.layer.cornerRadius = 10
        
        self.viewCount.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewCount.layer.borderWidth = 1
        self.viewCount.layer.cornerRadius = 10
    }
    
    func longGesture(){
        let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        longPressGesture.minimumPressDuration = 1.0
        longPressGesture.delegate = self
        self.tableView.addGestureRecognizer(longPressGesture)
    }
    
    @objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
        if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
            let touchPoint = longPressGestureRecognizer.location(in: self.tableView)
            if let indexPath = tableView.indexPathForRow(at: touchPoint) {
                let product = State.productsFilterResponse.productsView[indexPath.row]
                State.loadCustomProduct(productId: product.ProductId, completionHandler: { customProduct in
                    if let customProduct = customProduct{
                        self.editProduct(product: customProduct)
                    }
                })
            }
        }
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        if settings.storeSetupSettings.isEditingProductsEnabled{
            let editRowAction = UITableViewRowAction(style: UITableViewRowAction.Style.default, title: Util.getString("Edit"), handler:{action, indexpath in
                let product = State.productsFilterResponse.productsView[indexPath.row]
                State.loadCustomProduct(productId: product.ProductId, completionHandler: { customProduct in
                    if let customProduct = customProduct{
                        self.editProduct(product: customProduct)
                    }
                })
            })

            editRowAction.backgroundColor = UIColor.blue

            return [editRowAction]
        }
        return nil
    }
    
    func editProduct(product: CustomProduct) {
        let editProductTabBarViewController = self.storyboard?.instantiateViewController(withIdentifier: "editProductTabBarViewController") as! EditProductTabBarViewController
        editProductTabBarViewController.product = product
        self.navigationController?.pushViewController(editProductTabBarViewController, animated: true)
    }
    
    func loadProductsView(top: Int, skip: Int, filterString: String?, shouldLoadFilters: Bool){
        State.productsFilterRequest.storeId = Int(settings.StoreId)!
        State.productsFilterRequest.top  = top
        State.productsFilterRequest.skip = skip
        State.productsFilterRequest.filterString = filterString
        State.productsFilterRequest.orderBy = sortTypeString
        State.productsFilterRequest.selectedFamilyIds = selectedFamilyIds
        State.productsFilterRequest.selectedFamilyCodes = selectedFamilyCodes
        State.productsFilterRequest.selectedSubfamilyIds = selectedSubfamilyIds
        State.productsFilterRequest.selectedSubfamilyCodes = selectedSubfamilyCodes
        State.productsFilterRequest.criteriaXPO = criteriaXPO
        
        State.productsFilterRequest.selectedProducerIds = selectedProducerIds
        State.productsFilterRequest.selectedProducerLineIds = selectedProducerLineIds
        
        State.productsFilterRequest.selectedFeatureIds = selectedFeatureIds
        State.productsFilterRequest.selectedFeatureValueIds = selectedFeatureValueIds
        State.productsFilterRequest.shouldLoadFilters = shouldLoadFilters
        
        State.LoadProductsView(productFilterRequest: State.productsFilterRequest) { response in
            if let response = response {
                self.lastRequestReturnData = response
                self.updateTotalCountProducts()
                self.updateTotalFiltersCount()
                
                self.tableView.reloadData()
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
        
    func updateTotalCountProducts(){
        self.lfNumberOfProducts.text = Util.getString("Products") + ": \(State.productsFilterResponse.productsCount)"
        Util.notifyWhenLabelTextWasChanged(label: self.lfNumberOfProducts)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData()
        self.lfNumberOfProducts.text = Util.getString("Products") + ": \(State.productsFilterResponse.productsCount)"
    }
    
    func createTopButtonsInsets(){
        self.updateTotalFiltersCount()
        
        self.sortTypeString = "SoldQuantity desc"
        self.lfSort.text = Util.getString("Bestsellers")
    }
    
    func updateTotalFiltersCount(){
        self.totalFiltersCount = self.selectedProducerIds.count + self.selectedFeatureValueIds.count
        
        if self.totalFiltersCount == 1 {
            self.lfFilter.text = "\(totalFiltersCount.description) " + Util.getString("Filter")
        }
        else{
            self.lfFilter.text = "\(totalFiltersCount.description) " + Util.getString("Filters")
        }
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.productsFilterResponse.productsView.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! ProductCustomCell
        let product = State.productsFilterResponse.productsView[indexPath.row]
        
        cell.productTitle.text = product.Name
        cell.productSubtitle.text = product.Code
        
        if(product.ImageIcon == nil){
            cell.productImage.image = UIImage(named: "defaultProduct.png")
        }
        else{
            cell.productImage.image = product.ImageIcon
        }

        if (indexPath.row == State.productsFilterResponse.productsView.count-1 && State.productsFilterResponse.productsView.count > 99 && lastRequestReturnData){
            self.loadProductsView(top: 100, skip: State.productsFilterResponse.productsView.count, filterString: self.filterString, shouldLoadFilters: false)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        if settings.storeSetupSettings.isEditingProductsEnabled{
            return true
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let productView = State.productsFilterResponse.productsView[indexPath.row]
        
        State.LoadBarcodeInfo(productId: productView.ProductId, barcode: productView.Barcode, completionHandler: {result in
            if result == nil {
                NetworkController.AlertConnectionError(viewController: self)
            }
            else if result == true{
                if let barcodeInfo = State.barcodeInfo {
                    let tempShoppingCart = ShoppingCart()
                    tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
                    tempShoppingCart.recalculate(completionHandler: {
                        let productDetailViewController = (self.storyboard?.instantiateViewController(withIdentifier: "productDetailViewController") as! ProductDetailViewController)
                        productDetailViewController.cartItem = tempShoppingCart.cartItems[0]
                        productDetailViewController.delegate = self.delegate
                        self.navigationController?.pushViewController(productDetailViewController, animated: true)
                    })
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            else {
                Util.GeneralAlert(viewController: self, message: Util.getString("This product does not have a barcode!"))
            }
        })
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.filterString = searchText
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.setShowsCancelButton(true, animated: true)
        self.searchActive = true
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let searchText = searchBar.text, searchText.count > 2{
            self.searchBar.endEditing(true)
            self.searchActive = true
            self.filteredProducts(searchText: searchText)
        }
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.text = ""
        self.searchBar.showsCancelButton = false
        self.searchBar.endEditing(true)
        self.searchActive = false
        
        if(self.selectedFamilyIds.count != 0 && self.selectedSubfamilyIds.count != 0){
            self.filteredProducts(searchText: nil)
        }
    }
    
    func filteredProducts(searchText: String?){
        self.resetFilters()
        
        self.loadProductsView(top: 100, skip: 0, filterString: searchText, shouldLoadFilters: true)
    }
    
    func resetFilters(){
        self.selectedProducerIds = []
        self.selectedFeatureIds = []
        
        self.updateTotalFiltersCount()
    }
    
    @IBAction func btSortProducts_Click(_ sender: Any) {
        self.sortingProducts()
    }
    
    func sortingProducts(){
        let optionMenu = UIAlertController(title: "", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
        
        let bestSeller = UIAlertAction(title: Util.getString("Bestsellers"), style: .default, handler : { (action) -> Void in
            self.lfSort.text = Util.getString("Bestsellers")
            self.sortTypeString = "SoldQuantity desc"
            
            self.loadProductsView(top: 100, skip: 0, filterString: self.filterString, shouldLoadFilters: false)
        })
        let newest = UIAlertAction(title: Util.getString("Newest"), style: .default, handler : { (action) -> Void in
            self.lfSort.text = Util.getString("Newest")
            self.sortTypeString = "CreateTime desc"
            
            self.loadProductsView(top: 100, skip: 0, filterString: self.filterString, shouldLoadFilters: false)
        })
        let priceAscending = UIAlertAction(title: Util.getString("Price ascending"), style: .default, handler : { (action) -> Void in
            self.lfSort.text = Util.getString("Price asc.")
            self.sortTypeString = "Price asc"
         
            self.loadProductsView(top: 100, skip: 0, filterString: self.filterString, shouldLoadFilters: false)
        })
        let priceDescending = UIAlertAction(title: Util.getString("Price descending"), style: .default, handler : { (action) -> Void in
            self.lfSort.text = Util.getString("Price desc.")
            self.sortTypeString = "Price desc"
            
            self.loadProductsView(top: 100, skip: 0, filterString: self.filterString, shouldLoadFilters: false)
        })
        let cancel = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        optionMenu.addAction(bestSeller)
        optionMenu.addAction(newest)
        optionMenu.addAction(priceAscending)
        optionMenu.addAction(priceDescending)
        optionMenu.addAction(cancel)
        
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad){
            if let currentPopoverpresentioncontroller = optionMenu.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = self.viewSort
                currentPopoverpresentioncontroller.sourceRect = self.viewSort.bounds
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.up;
                self.present(optionMenu, animated: true, completion: nil)
            }
            else{
                self.present(optionMenu, animated: true, completion: nil)
            }
        }
        else{
            self.present(optionMenu, animated: true, completion: nil)
        }
    }
    
    @IBAction func btFilterProducts_Click(_ sender: Any) {
        self.openFilter()
    }
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .fullScreen
    }
    
    func openFilter(){
        let filterSelectorViewController = self.storyboard?.instantiateViewController(withIdentifier: "filterSelectorViewController") as! ProductFiltersViewController
        filterSelectorViewController.delegate = self
        filterSelectorViewController.availableFilters = self.availableFilters
        filterSelectorViewController.availableDetailFilters = self.availableDetailFilters
        filterSelectorViewController.title = Util.getString("Filters")
        let nav = UINavigationController(rootViewController: filterSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    func applyFilters(availableDetailFilters: [AnyObject]) {
        self.availableDetailFilters = availableDetailFilters as! [IFilters]
        self.selectedFeatureValueIds = []
        self.selectedProducerIds = []
        
        for filter in State.productsFilterResponse.producersView{
            if filter.shouldBeChecked{
                filter.isChecked = true
                self.selectedProducerIds.append(filter.filterId)
            }
            else{
                filter.isChecked = false
            }
        }
        for filter in State.productsFilterResponse.featureValuesView{
            if filter.shouldBeChecked{
                filter.isChecked = true
                self.selectedFeatureValueIds.append(filter.filterId)
            }
            else{
                filter.isChecked = false
            }
        }
        
        self.loadProductsView(top: 100, skip: 0, filterString: searchBar.text, shouldLoadFilters: false)
    }
}
