//
//  ProductContainerDetailsViewController.swift
//  iPOS
//
//  Created by Zoran Albu on 8/5/19.
//  Copyright © 2019 BBC. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

class ProductContainerDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, ScannerViewControllerDelegate, UIPopoverPresentationControllerDelegate, ProductContainerDetailCellDelegate{

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tfBarcode: UITextField!
    @IBOutlet weak var btBarcodeScanner: UIButton!
    @IBOutlet weak var btCheck: UIButton!
    @IBOutlet weak var lfDetailsCount: UILabel!
    
    var productContainer: ProductContainer = ProductContainer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setFieldsDelegate()
        self.setCaptions()
        self.createButtonGesture()
        self.setTableViewProperties()
    }
    
    func setCaptions(){
        self.tfBarcode.placeholder = Util.getString("TypeBarcode")
        self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , 0, 0)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.registerKeyboard()
        self.createRightButtons()
        self.createLeftBackButton()
        self.customLayout()
        self.loadProductContainerDetails()
        self.setControllerStatus(isEnabled: isEditing)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.unregisterKeyboard()
        self.view.endEditing(true)
    }
    
    func setFieldsDelegate(){
        self.tfBarcode.delegate = self
        self.tableView.dataSource = self
        self.tableView.delegate = self
    }
    
    func setTableViewProperties(){
        self.tableView.allowsSelection = true
        self.tableView.allowsSelectionDuringEditing = true
    }
    
    func customLayout(){
        self.title = self.productContainer.productContainerName
        
        self.tfBarcode.font = UIFont.boldSystemFont(ofSize: 21)
        self.tfBarcode.textAlignment = .left
        
        self.btBarcodeScanner.layer.cornerRadius = 5
        self.btBarcodeScanner.layer.borderWidth = 1
        self.btBarcodeScanner.layer.borderColor = UIColor(red: 0.12, green: 0.56, blue: 1.00, alpha: 1.0).cgColor
        
        self.btCheck.layer.cornerRadius = 5
        self.btCheck.layer.borderWidth = 1
        self.btCheck.layer.borderColor = UIColor(red: 0.12, green: 0.56, blue: 1.00, alpha: 1.0).cgColor
    }
    
    func loadProductContainerDetails(){
        State.getProductContainerDetailsDecodedStyles(self.productContainer) { result in
            if let decodeStylesResult = result{
                if let msg = decodeStylesResult.resultMessage{
                    Util.GeneralAlert(viewController: self, message: msg)
                    return
                }
                if let products = decodeStylesResult.products{
                    self.productContainer.productContainerDetails = self.productContainer.addDetails(products: products)
                    if self.productContainer.productContainerDetails.count == 0 {
                        super.setEditing(true, animated: true)
                        self.tableView.setEditing(true, animated: true)
                        self.setControllerStatus(isEnabled: true)
                    }
                    self.tableView.reloadData()
                    self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , self.productContainer.getDetailsCount(), self.productContainer.getDetailsQuantities())
                }
                else{
                    Util.AlertSystemError(viewController: self)
                }
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
    
    func createRightButtons(){
        self.navigationItem.rightBarButtonItems = [self.editButtonItem]
    }
    
    func removeRightButtons(){
        self.navigationItem.rightBarButtonItems = []
    }
    
    func createLeftBackButton(){
        if isEditing{
            let backButton = UIBarButtonItem(title: Util.getString("Cancel"), style: .done, target: self, action: #selector(backButtonPressed))
            self.navigationItem.leftBarButtonItem = backButton
            self.navigationItem.leftItemsSupplementBackButton = false
        }
        else{
            self.navigationItem.leftBarButtonItem = nil
            self.navigationItem.leftItemsSupplementBackButton = true
        }
    }
    
    @objc func backButtonPressed(){
        if isEditing{
            Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("Are you sure you want to cancel? All changes will be lost!"), actionYes: {
                _ = self.navigationController?.popViewController(animated: true)
            }, actionNo: {
                return
            })
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.productContainer.productContainerDetails.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ProductContainerDetailCell
      
        let detail = self.productContainer.productContainerDetails[indexPath.row]
        
        cell.lfTitle?.font = UIFont.boldSystemFont(ofSize: 21.0)
        cell.lfTitle?.text = detail.barcode
        cell.lfSubtitle?.text = detail.productName + " / \(detail.productCode)"
        cell.tfQuantity?.text = detail.quantity.description
        cell.stQuantity.value = Double(detail.quantity)
        cell.delegate = self
        
        if self.isEditing{
            cell.isUserInteractionEnabled = true
            cell.stQuantity.isEnabled = true
            cell.tfQuantity.isEnabled = true
            cell.stQuantity.alpha = 1.0
        }
        else{
            cell.isUserInteractionEnabled = false
            cell.stQuantity.isEnabled = false
            cell.tfQuantity.isEnabled = false
            cell.stQuantity.alpha = 0.5
        }
        
        return cell
    }
    
    @IBAction func btCheck_Click(_ sender: Any) {
        if self.tfBarcode.text == ""{
            return
        }
        
        self.decodeBarcode(barcode: self.tfBarcode.text ?? "")
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "\n"{
            self.decodeBarcode(barcode: self.tfBarcode.text ?? "")
        }
        
        return true
    }
    
    func decodeBarcode(barcode: String){
        let barcodeRequest: DecodeStylesAndBarcodes.DecodeBarcodeRequest = DecodeStylesAndBarcodes.DecodeBarcodeRequest(barcode: barcode)
        State.decodeBarcode(decodeBarcodeRequest: barcodeRequest) { result in
            if let decodeBarcodeResponse = result{
                if let msg = decodeBarcodeResponse.resultMessage{
                    Util.GeneralAlert(viewController: self, message: msg, title: barcode)
                    return
                }
                if let product = decodeBarcodeResponse.product{
                    self.addNewProductContainerDetailAndRefresh(product: product)
                    self.clearAndFocusBarcodeTextField()
                }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("Barcode not found!"), title: barcode)
                    self.clearAndFocusBarcodeTextField()
                }
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
                self.clearAndFocusBarcodeTextField()
            }
        }
    }
    
    func addNewProductContainerDetailAndRefresh(product: WSBarcodeInfo){
        let productContainerDetail = self.productContainer.addDetail(product: product)
        if productContainerDetail.alreadyExist == false{
            self.productContainer.productContainerDetails.insert(productContainerDetail, at: 0)
        }
        self.productContainer.setRowIndex()
        
        self.tableView.reloadData()
        self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , self.productContainer.getDetailsCount(), self.productContainer.getDetailsQuantities())
        self.notifyCellQuantityChanged(rowId: productContainerDetail.rowId)
    }
    
    func clearAndFocusBarcodeTextField(){
        self.tfBarcode.text = ""
        self.tfBarcode.becomeFirstResponder()
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            self.productContainer.productContainerDetails.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: .fade)
            self.tableView.reloadData()
            self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , self.productContainer.getDetailsCount(), self.productContainer.getDetailsQuantities())
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if self.isEditing{
            return true
        }
        return false
    }
    
    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        self.tableView.setEditing(editing, animated: animated)
        
        if isEditing == false {
            //Save
            self.view.endEditing(true)
            self.productContainer.setRowIndex()
            State.addProductContainer(self.productContainer, completionHandler: { result in
                if let productContainerResult = result{
                    if let msg = productContainerResult.errorMessage{
                        Util.GeneralAlert(viewController: self, message: msg)
                    }
                    else{
                       self.navigationController?.popViewController(animated: true)
                    }
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            })
        }
        
        self.setControllerStatus(isEnabled: editing)
        self.createLeftBackButton()
        self.tableView.reloadData()
    }
    
    func setControllerStatus(isEnabled: Bool){
        self.tfBarcode.isEnabled = isEnabled
        self.btCheck.isEnabled = isEnabled
        self.btBarcodeScanner.isEnabled  = isEnabled
    }
    
    func createButtonGesture(){
        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(sender:)))
        longPressGestureRecognizer.minimumPressDuration = 0.2
        self.btBarcodeScanner.addGestureRecognizer(longPressGestureRecognizer)
    }
    
    @objc func handleLongPress(sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.began{
            print("begin touching button")
            self.dismissKeyboard()
            self.openPopUp()
        }
        else if sender.state == UIGestureRecognizer.State.ended || sender.state == UIGestureRecognizer.State.cancelled{
            print("end touching button")
            self.hidePopUp()
        }
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
    }
    
    func openPopUp() {
        let scannerViewController = self.storyboard?.instantiateViewController(withIdentifier: "scannerViewController") as! ScannerViewController
        scannerViewController.delegate = self
        scannerViewController.isSlideButtonVisible = false
        scannerViewController.view.backgroundColor = UIColor(white: 1, alpha: 0.5)
        
        let nav = UINavigationController(rootViewController: scannerViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        let popover = nav.popoverPresentationController
        popover?.permittedArrowDirections = .any
        scannerViewController.preferredContentSize = CGSize(width: self.tableView.frame.size.width/2, height: self.tableView.frame.size.height/2)
        popover?.delegate = self
        popover?.sourceView = self.view
        popover?.permittedArrowDirections = .any
        popover?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        self.present(nav, animated: true, completion: nil)
    }
    
    func barcodeFound(barcode: String, captureSession: AVCaptureSession) {
        let barcodeRequest: DecodeStylesAndBarcodes.DecodeBarcodeRequest = DecodeStylesAndBarcodes.DecodeBarcodeRequest(barcode: barcode)
        State.decodeBarcode(decodeBarcodeRequest: barcodeRequest) { result in
            self.hidePopUp()
            if let decodeBarcodeResponse = result{
                if let msg = decodeBarcodeResponse.resultMessage{
                    Util.GeneralAlert(viewController: self, message: msg, title: barcode)
                    return
                }
                if let product = decodeBarcodeResponse.product{
                    self.addNewProductContainerDetailAndRefresh(product: product)
                }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("Barcode not found!"), title: barcode)
                }
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
    
    func hidePopUp(){
        if let presentedViewController = self.presentedViewController{
            presentedViewController.dismiss(animated: true, completion: nil)
        }
    }
    
    func stepperValueChanged(cell: UITableViewCell, value: Int) {
        if let indexPath = self.tableView.indexPath(for: cell){
            let cell = tableView.cellForRow(at: indexPath) as! ProductContainerDetailCell
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
            
            let detail = self.productContainer.productContainerDetails[indexPath.row]
            cell.tfQuantity.text = value.description
            detail.quantity = value
            
            self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , self.productContainer.getDetailsCount(), self.productContainer.getDetailsQuantities())
        }
    }
    
    func textFieldValueChanged(cell: UITableViewCell, value: Int) {
        if let indexPath = self.tableView.indexPath(for: cell){
            let cell = tableView.cellForRow(at: indexPath) as! ProductContainerDetailCell
            
            let detail = self.productContainer.productContainerDetails[indexPath.row]
            cell.tfQuantity.text = value.description
            cell.stQuantity.value = Double(value)
            detail.quantity = value
            
            self.lfDetailsCount.text = String.init(format: Util.getString("RowsAndQuantities") , self.productContainer.getDetailsCount(), self.productContainer.getDetailsQuantities())
        }
    }
    
    func textFieldBeginEditing(cell: UITableViewCell){
        if let indexPath = self.tableView.indexPath(for: cell){
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }
    
    func notifyCellQuantityChanged(rowId: Int?){
        if let index = rowId{
            let indexPath: IndexPath = IndexPath(item: index, section: 0)
            
            let indexPathsForVisibleRows = self.tableView.indexPathsForVisibleRows
            let firstVisibleRow = indexPathsForVisibleRows?.first?.row ?? 0
            let lastVisibleRow = indexPathsForVisibleRows?.last?.last ?? 0
            
            switch indexPath.row {
            case firstVisibleRow ... lastVisibleRow:
                print("Row \(indexPath.row) already between \(firstVisibleRow) and \(lastVisibleRow)")
                self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
            default:
                print("Will scroll to \(indexPath.row)")
                self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
            }
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }
    
    // Keyboard
    func registerKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func unregisterKeyboard(){
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func keyboardDidShow(notification: NSNotification){
        let userInfo: NSDictionary = notification.userInfo! as NSDictionary
        let keyboardInfo = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
        let keyboardSize = keyboardInfo.cgRectValue.size
        let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
        self.tableView.contentInset = contentInsets
        self.tableView.scrollIndicatorInsets = contentInsets
    }
    
    @objc func keyboardWillHide(notification: NSNotification){
        self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
}
