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

import Foundation

class EntranceGoodsDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, EntranceGoodsDetailCellDelegate{
   
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lfSupplierCaption: UILabel!
    @IBOutlet weak var lfSupplierName: UILabel!
    @IBOutlet weak var lfDocQtyCaption: UILabel!
    @IBOutlet weak var lfDocQty: UILabel!
    @IBOutlet weak var lfRevQtyCaption: UILabel!
    @IBOutlet weak var lfRevQty: UILabel!
    @IBOutlet weak var lfDifQtyCaption: UILabel!
    @IBOutlet weak var lfDifQty: UILabel!
    @IBOutlet weak var lfDocQtyPrice: UILabel!
    @IBOutlet weak var lfRevQtyPrice: UILabel!
    @IBOutlet weak var lfDifQtyPrice: UILabel!
    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var lfEntranceGoodsStatusCaption: UILabel!
    @IBOutlet weak var lfEntranceGoodsStatus: UILabel!
    @IBOutlet weak var btCertify: UIButton!
    
    var entranceGoods: EntranceGoods = EntranceGoods()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setCaptions()
        self.setDelegates()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.initHeader()
        self.createRightButtons()
        self.setCertifyButtonStatus()
        self.setTitle()
        self.loadDetails()
        self.registerKeyboard()
    }
    
    func setDelegates(){
        self.tableView.dataSource = self
        self.tableView.delegate = self
    }
    
    func setCaptions(){
        self.lfSupplierCaption.text = Util.getString("Supplier")
        self.lfDocQtyCaption.text = Util.getString("Document Quantity")
        self.lfRevQtyCaption.text = Util.getString("Revealed Quantity")
        self.lfDifQtyCaption.text = Util.getString("Difference Quantity")
        self.lfEntranceGoodsStatusCaption.text = Util.getString("Entrance Goods")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.unregisterKeyboard()
        self.view.endEditing(true)
    }
    
    func createRightButtons(){
        if self.entranceGoods.isCertified{
            self.navigationItem.rightBarButtonItems = []
        }
        else{
            //self.navigationItem.rightBarButtonItems = [self.editButtonItem]
        }
    }
    
    func setCertifyButtonStatus(){
        if self.entranceGoods.isCertified{
            if let certifyTime = self.entranceGoods.certifyTime, let certifyNumber = self.entranceGoods.entranceNumber{
                self.lfEntranceGoodsStatus.text = "\(certifyNumber) - \(Util.DateToShortDateString(date: certifyTime))"
            }
            self.btCertify.isEnabled = false
            self.btCertify.alpha = 0.0
        }
        else{
            self.lfEntranceGoodsStatus.text = Util.getString("-")
            
            if self.isEditing{
                self.btCertify.isEnabled = true
                self.btCertify.alpha = 1.0
                self.btCertify.setTitleColor(UIColor.green, for: .normal)
                self.btCertify.layer.borderColor = UIColor.green.cgColor
                self.btCertify.layer.borderWidth = 1
            }
            else{
                self.btCertify.isEnabled = false
                self.btCertify.alpha = 0.5
                self.btCertify.setTitleColor(UIColor.lightGray, for: .normal)
                self.btCertify.layer.borderColor = UIColor.lightGray.cgColor
                self.btCertify.layer.borderWidth = 1
            }
        }
    }
    
    func setTitle(){
        if let supplierName = self.entranceGoods.sourceSupplierName{
            self.title = "\(supplierName) \(self.entranceGoods.documentNumber) - \(Util.DateToShortDateString(date: self.entranceGoods.documentDate))"
        }
        else{
            self.title = "\(self.entranceGoods.documentNumber) - \(Util.DateToShortDateString(date: self.entranceGoods.documentDate))"
        }
    }
    
    func initHeader(){
        self.lfSupplierName.text = self.entranceGoods.sourceSupplierName
        let docQuantity = self.entranceGoods.documentQuantity ?? 0
        let revQuantity = self.entranceGoods.revealedQuantity ?? 0
        let diffQuantity = self.entranceGoods.differenceQuantity
        
        self.lfDocQty.text = docQuantity.description
        self.lfRevQty.text = revQuantity.description
        self.lfDifQty.text = diffQuantity.description
        
        self.lfDocQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(0)) \(settings.userSettings.defaultCurrency)"
        self.lfRevQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(0)) \(settings.userSettings.defaultCurrency)"
        self.lfDifQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(0)) \(settings.userSettings.defaultCurrency)"
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let topBorder: CALayer = CALayer()
        topBorder.frame = CGRect.init(x: 0, y: self.headerView.frame.size.height + 4, width: self.headerView.frame.size.width, height: 1)
        topBorder.backgroundColor = UIColor.lightGray.cgColor
        self.headerView.layer.addSublayer(topBorder)
    }
    
    func calculateHeaderTotals(){
        self.lfDocQty.text = self.entranceGoods.detailDocumentQuantity.description
        self.lfRevQty.text = self.entranceGoods.detailRevealedQuantity.description
        self.lfDifQty.text = self.entranceGoods.detailDifferenceQuantity.description
        
        self.lfDocQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(self.entranceGoods.detailDocumentQuantityPrice)) \(settings.userSettings.defaultCurrency)"
        self.lfRevQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(self.entranceGoods.detailRevealedQuantityPrice)) \(settings.userSettings.defaultCurrency)"
        self.lfDifQtyPrice.text = "\(Util.DoubleToStringWithPointSeparator(self.entranceGoods.detailDifferenceQuantityPrice)) \(settings.userSettings.defaultCurrency)"
        
        if self.entranceGoods.detailDifferenceQuantity == 0 {
            self.lfDifQty.textColor = UIColor.green
            self.lfDifQtyPrice.textColor = UIColor.green
        }
        else if self.entranceGoods.detailDifferenceQuantity > 0 {
            self.lfDifQty.textColor = UIColor.orange
            self.lfDifQtyPrice.textColor = UIColor.orange
        }
        else if self.entranceGoods.detailDifferenceQuantity < 0 {
            self.lfDifQty.textColor = UIColor.red
            self.lfDifQtyPrice.textColor = UIColor.red
        }
    }
    
    func loadDetails(){
        State.loadEntranceGoodsAndDetails(entranceGoodsId: self.entranceGoods.entranceGoodsId) { response in
            if let entranceGoodsAndDetails = response{
                self.entranceGoods = entranceGoodsAndDetails
                self.calculateHeaderTotals()
                self.tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var count = 0
        for detail in self.entranceGoods.entranceGoodsOrderDetails{
            if detail.rowState == .Deleted || detail.rowState == .Detached{
                continue
            }
            count += 1
        }
        return count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! EntranceGoodsDetailCell
        
        let detail = self.entranceGoods.entranceGoodsOrderDetails[indexPath.row]
        
        cell.lfProductName.text = detail.productName
        cell.lfProductCode.text = detail.productCode
        cell.lfProductPrice.text = "\(Util.DoubleToStringWithPointSeparator(detail.productSalePrice)) \(settings.userSettings.defaultCurrency)"
        cell.lfProductQuantity.text = detail.productDocumentQuantity.description
        cell.tfProductQuantity.text = detail.productRevealedQuantity.description
        cell.stProductQuantity.value = Double(detail.productRevealedQuantity)
        
        if self.entranceGoods.isCertified || self.isEditing == false{
            cell.isUserInteractionEnabled = false
            cell.tfProductQuantity.isEnabled = false
            cell.stProductQuantity.isEnabled = false
            cell.stProductQuantity.alpha = 0.5
        }
        else{
            cell.isUserInteractionEnabled = true
            cell.tfProductQuantity.isEnabled = true
            cell.stProductQuantity.isEnabled = true
            cell.stProductQuantity.alpha = 1.0
        }
        
        cell.delegate = self
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let detail = self.entranceGoods.entranceGoodsOrderDetails[indexPath.row]
            detail.setNewRowState(from: "delete")
            self.tableView.reloadData()
            self.calculateHeaderTotals()
        }
    }
    
    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)
        
        if isEditing == false {
            //Save
            State.saveEntranceGoodsDetails(entranceGoodsDetails: self.entranceGoods.entranceGoodsOrderDetails) { response in
                if let egodResponse = response{
                    if let message = egodResponse.resultMessage{
                        if message != "Ok"{
                            Util.GeneralAlert(viewController: self, message: message)
                        }
                    }
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
        }
        
        self.createRightButtons()
        self.setCertifyButtonStatus()
        self.tableView.reloadData()
    }
    
    func stepperValueChanged(cell: UITableViewCell, value: Int) {
        if let indexPath = self.tableView.indexPath(for: cell){
            let cell = tableView.cellForRow(at: indexPath) as! EntranceGoodsDetailCell
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
            
            let detail = self.entranceGoods.entranceGoodsOrderDetails[indexPath.row]
            cell.tfProductQuantity.text = value.description
            detail.productRevealedQuantity = value
            detail.setNewRowState(from: "modify")
            self.calculateHeaderTotals()
        }
    }
    
    func textFieldValueChanged(cell: UITableViewCell, value: Int) {
        if let indexPath = self.tableView.indexPath(for: cell){
            let cell = tableView.cellForRow(at: indexPath) as! EntranceGoodsDetailCell
            
            let detail = self.entranceGoods.entranceGoodsOrderDetails[indexPath.row]
            cell.tfProductQuantity.text = value.description
            cell.stProductQuantity.value = Double(value)
            detail.productRevealedQuantity = value
            detail.setNewRowState(from: "modify")
            
            self.calculateHeaderTotals()
        }
    }
    
    func textFieldBeginEditing(cell: UITableViewCell){
        if let indexPath = self.tableView.indexPath(for: cell){
            let cell = tableView.cellForRow(at: indexPath) as! EntranceGoodsDetailCell
            self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
            
            if let revealedQuantity = Int(cell.tfProductQuantity.text ?? "0"){
                if(revealedQuantity == 0){
                    let detail = self.entranceGoods.entranceGoodsOrderDetails[indexPath.row]
                    cell.tfProductQuantity.text = detail.productDocumentQuantity.description
                    cell.stProductQuantity.value = Double(detail.productDocumentQuantity)
                    detail.productRevealedQuantity = detail.productDocumentQuantity
                    self.calculateHeaderTotals()
                }
            }
        }
    }
    
    
    @IBAction func btCertify_Click(_ sender: Any) {
        print("Certify")
    }
    
    // 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)
    }
}
