//
//  ProductViewUserControl.swift
//  iPOS
//
//  Created by bbc on 24.03.2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import UIKit
import AVFoundation

class ProductFamilyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate, UIPopoverPresentationControllerDelegate, ScannerViewControllerDelegate{
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var btScanBarcode: UIButton!
    
    var searchActive: Bool = false
    var isSlideButtonEnabled = true
    var delegate: IProductSelectorListener!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.searchBar.delegate = self
        self.title = Util.getString("Products")
        self.searchBar.placeholder = Util.getString("Search")
    }

    func createAddButton(){
        let addNewProductButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewProduct(_:)))
        self.navigationItem.rightBarButtonItem = addNewProductButton
    }
    
    @objc func addNewProduct(_ sender: Any) {
        var alert = UIAlertController()
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
            alert = UIAlertController(title: "Add new product", message: "", preferredStyle: .alert)
        }
        else{
            alert = UIAlertController(title: "Add new product", message: "", preferredStyle: .actionSheet)
        }
        
        let addNewFrameAction = UIAlertAction(title: Util.getString("Frame"), style: .default, handler: {(_) in
            self.addFrame()
        })
        addNewFrameAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "glasses50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        alert.addAction(addNewFrameAction)
        
        let addNewProductAction = UIAlertAction(title: Util.getString("Others"), style: .default, handler: {(_) in
            self.addDefaultProduct()
        })
        
        addNewProductAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "defaultProduct50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        alert.addAction(addNewProductAction)
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            return
        }))
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func addFrame(){
        let code = "MNT"
        if let family = self.findFamilyByCode(code: code){
            let frameProductTableViewController = self.storyboard?.instantiateViewController(withIdentifier: "frameProductTableViewController") as! FrameProductTableViewController
            frameProductTableViewController.productFrame.productFamilyId = family.productFamilyId
            frameProductTableViewController.productFrame.productFamilyName = family.name ?? ""
            frameProductTableViewController.title = family.name ?? ""
            self.navigationController?.pushViewController(frameProductTableViewController, animated: true)
        }
        else{
            let message = String.init(format: Util.getString("InvalidFamilyCode"), code)
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    func findFamilyByCode(code: String) -> ProductFamily?{
        for frame in State.productFamily{
            if frame.code == code{
                return frame
            }
        }
        return nil
    }
    
    func addDefaultProduct(){
        let editProductTabBarViewController = self.storyboard?.instantiateViewController(withIdentifier: "editProductTabBarViewController") as! EditProductTabBarViewController
        editProductTabBarViewController.product = CustomProduct()
        self.navigationController?.pushViewController(editProductTabBarViewController, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData()
        if(isSlideButtonEnabled){
            self.setNavigationBarItem()
            if settings.storeSetupSettings.isEditingProductsEnabled{
                self.createAddButton()
            }
        }
        State.loadProductFamilies(filterString: nil) { result in
            if result {
                self.tableView.reloadData()
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
    
    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.productFamily.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell
        let family = State.productFamily[indexPath.row]
    
        cell.textLabel?.text = family.name
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let family = State.productFamily[indexPath.row]
        let productSubfamily = (self.storyboard?.instantiateViewController(withIdentifier: "productViewSubfamilyUserControl") as! ProductSubfamilyViewController)
        productSubfamily.title = family.name
        productSubfamily.productFamilyId = family.productFamilyId
        productSubfamily.delegate = delegate
        self.navigationController?.pushViewController(productSubfamily, animated: true)
    }
    
    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
    }
    
    func filteredProducts(searchText: String?){
        let productViewController = self.storyboard?.instantiateViewController(withIdentifier: "productViewController") as! ProductViewController
        State.productsFilterResponse = ProductsFilterResponse()
        productViewController.filterString = searchText
        productViewController.delegate = delegate
        productViewController.title = Util.getString("Products")
        self.navigationController?.pushViewController(productViewController, animated: true)
    }
    
    @IBAction func btScanBarcode_Click(_ sender: Any) {
        let scannerViewController = (self.storyboard?.instantiateViewController(withIdentifier: "scannerViewController") as! ScannerViewController)
        scannerViewController.delegate = self
        scannerViewController.isSlideButtonVisible = false
        self.navigationController?.pushViewController(scannerViewController, animated: true)
    }
    
    func barcodeFound(barcode: String, captureSession: AVCaptureSession) {
        State.LoadBarcodeInfo(barcode: barcode, completionHandler: {
            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{
                Util.scannedBarcodeNotFoundAlert(code: barcode, message: Util.getString("Barcode not found!"), viewController: self, captureSession: captureSession)
            }
        })
    }
}

extension ProductFamilyViewController : SlideMenuControllerDelegate {
    
    func leftWillOpen() {
    }
    
    func leftDidOpen() {
    }
    
    func leftWillClose() {
    }
    
    func leftDidClose() {
    }
    
    func rightWillOpen() {
    }
    
    func rightDidOpen() {
    }
    
    func rightWillClose() {
    }
    
    func rightDidClose() {
    }
}
