//
//  ReceiptDetailViewController.swift
//  iPOS
//
//  Created by bbc on 14.02.2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit

class ReceiptDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var nrOfProducts: UILabel!
    @IBOutlet weak var receiptTotal: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    var btnBarBadge : MJBadgeBarButton!
    
    var receipt = Receipt()
    var contact: Contact?
    var familliesId: [Int] = [Int]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.allowsSelection = false
        self.tableView.allowsMultipleSelection = false

        self.createNavigationButtons()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let contact = contact{
            self.title = Util.getString("Purchases")
            //Load Movements filtered by contactId and familiesId
            State.loadMovements(contactId: contact.ContactId, familiesId: familliesId, completionHandler: { (result) in
                if result{
                    if State.movementView.count == 0{
                        self.navigationItem.rightBarButtonItem = nil
                        self.navigationItem.rightBarButtonItems = nil
                    }
                    self.tableView.reloadData()
                    self.refreshReceiptTotals()
                }
                else{
                    self.navigationItem.rightBarButtonItem = nil
                    self.tableView.reloadData()
                    Util.GeneralAlert(viewController: self, message: Util.getString("An error has occured.\nPlease try again!"))
                }
            })
        }
        else{
            if let receiptNumber = receipt.receiptNumber, let receiptDay = receipt.day{
                self.title = "\(receiptNumber)-\(Util.DateToShortDateString(date: receiptDay))"
            }
            else{
                self.title = ""
            }
            //Load Movements filtered by receiptId
            State.loadMovements(receiptId: receipt.receiptId) { result in
                if State.movementView.count == 0{
                    self.navigationItem.rightBarButtonItem = nil
                    self.navigationItem.rightBarButtonItems = nil
                }
                
                self.tableView.reloadData()
                self.refreshReceiptTotals()
            }
        }
        self.btnBarBadge.badgeValue = "\(self.productAddedCount())"
    }
    
    private func productAddedCount() -> Int {
        var quantity: Double = 0
        for cart in State.shoppingCart.cartItems{
            quantity += cart.Quantity
        }
        return Int(quantity)
    }
    
    func createNavigationButtons(){
        let infoButton = UIBarButtonItem(image: UIImage.init(named: "Info.png"), style: .plain, target: self, action: #selector(self.infoButton_Click(_:)))
        
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        
        let customButton = UIButton(type: UIButton.ButtonType.custom)
        customButton.frame = CGRect(x: 0, y: 0, width: 35.0, height: 35.0)
        customButton.addTarget(self, action: #selector(self.viewShoppingBag(_:)), for: .touchUpInside)
        customButton.setImage(UIImage(named: "shoppingBag.png"), for: .normal)
        
        btnBarBadge = MJBadgeBarButton()
        btnBarBadge.setup(customButton: customButton)
        btnBarBadge.badgeValue = State.shoppingCart.cartItems.count.description
        btnBarBadge.badgeOriginX = 20.0
        btnBarBadge.badgeOriginY = -4
        
        if contact == nil {
            self.navigationItem.rightBarButtonItems = [infoButton, btnBarBadge, flexibleSpace]
        }
        else{
            self.navigationItem.rightBarButtonItem = btnBarBadge
        }
    }
    
    @objc func viewShoppingBag(_ sender: Any){
        let shoppingCartViewController = AppDelegate.leftViewController.shoppingCartView!
        shoppingCartViewController.isSlideButtonEnabled = false
        
        if let contact = self.contact{
            State.shoppingCart.contact = contact
        }
        else{
            State.shoppingCart.contact = self.receipt.contact
        }
        
        if let _ = Util.getViewControllerFromStack(navigationController: self.navigationController, viewController: shoppingCartViewController){
            shoppingCartViewController.isSlideButtonEnabled = true
            self.navigationController?.popToViewController(shoppingCartViewController, animated: true)
        }
        else{
            self.navigationController?.pushViewController(shoppingCartViewController, animated: true)
        }
    }
    
    func refreshReceiptTotals(){
        if(State.movementView.count == 0){
            self.nrOfProducts.text = "\(State.movementView.count.description) " + Util.getString("Products")
        }
        else if(State.movementView.count == 1){
            self.nrOfProducts.text = "\(State.movementView.count.description) " + Util.getString("Product")
        }
        else if (State.movementView.count > 1){
            self.nrOfProducts.text = "\(State.movementView.count.description) " + Util.getString("Products")
        }
        if contact == nil{
            let total: Double = receipt.totalAmount! * Double(receipt.transactionSign!)
            self.receiptTotal.text = Util.DoubleToString(total) + " \(settings.userSettings.defaultCurrency)"
        }
        else{
            var total: Double = 0
            for movement in State.movementView{
                total += movement.netRowValueVatIncluded!
            }
            self.receiptTotal.text = Util.DoubleToString(total) + " \(settings.userSettings.defaultCurrency)"
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.movementView.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! CartItemCustomCell
        let movement = State.movementView[indexPath.row]
        if(movement.barcodeInfo.ImageIcon == nil){
            cell.imageIcon.image = UIImage(named: "defaultProduct.png")
        }
        else{
            cell.imageIcon.image = movement.barcodeInfo.ImageIcon
        }
            
        cell.productName.text = movement.barcodeInfo.Name
        cell.productCode.text = movement.barcodeInfo.Code
        cell.quantity.text = (movement.quantity?.description)! + " x "
        
        let netRowValue = Util.DoubleToStringWithPointSeparator(movement.netRowValueVatIncluded!)
        let grossRowValue = Util.DoubleToStringWithPointSeparator(movement.grossUnitValueVatIncluded! * movement.quantity!)
        if((Double(netRowValue)?.isLess(than: (Double(grossRowValue)!)))!){
            let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToString(movement.grossUnitValueVatIncluded!) + " \(settings.userSettings.defaultCurrency)")
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
            cell.grossUnitValue.attributedText = attributeString
            cell.netRowValue.textColor = UIColor.red
        }
        else{
            cell.grossUnitValue.text = Util.DoubleToString(movement.grossUnitValueVatIncluded!) + " \(settings.userSettings.defaultCurrency)"
            cell.netRowValue.textColor = UIColor.black
        }
        cell.netRowValue.text = Util.DoubleToString(movement.netRowValueVatIncluded!) + " \(settings.userSettings.defaultCurrency)"
        
        cell.sizeCode.text = movement.barcodeInfo.SizeCode
        cell.productColor.text = movement.barcodeInfo.ColorName
        
        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, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let movement = State.movementView[indexPath.row]
        
        let addToCartAction = UITableViewRowAction(style: UITableViewRowAction.Style.destructive, title: Util.getString("Add to cart"), handler:{action, indexpath in
           self.addItemToCart(item: movement)
        })
        
        addToCartAction.backgroundColor = UIColor.green
        
        return [addToCartAction]
    }
    
    func addItemToCart(item: Movement){
        item.barcodeInfo.quantity = abs(item.quantity ?? 1)
        State.shoppingCart.addItem(barcodeInfo: item.barcodeInfo.clone())
        State.shoppingCart.recalculate() {
            Util.GeneralAlertAutoDismiss(viewController: self, message: Util.getString("Product added to the shopping cart"), time: 0.5)
            self.btnBarBadge.badgeValue = "\(self.productAddedCount())"
        }
    }
    
    @objc func infoButton_Click(_ sender: UIBarButtonItem) {
        let transactionStatusViewController = self.storyboard?.instantiateViewController(withIdentifier: "TransactionStatusViewController") as! TransactionStatusViewController
        transactionStatusViewController.receiptId = receipt.receiptId.description
        transactionStatusViewController.isNewTransaction = false
        self.navigationController?.pushViewController(transactionStatusViewController, animated: true)
    }
}
