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

import UIKit

class ProductDetailViewController: UIViewController,UITabBarDelegate, UIPopoverPresentationControllerDelegate, UIScrollViewDelegate{
    
    @IBOutlet weak var lfName: UILabel!
    @IBOutlet weak var lfCode: UILabel!
    @IBOutlet weak var lfColor: UILabel!
    @IBOutlet weak var lfSize: UILabel!
    @IBOutlet weak var lfPrice: UILabel!
    @IBOutlet weak var lfStock: UILabel!
    @IBOutlet weak var tvDescription: UITextView!
    @IBOutlet weak var lfBarcode: UILabel!
    @IBOutlet weak var tabBar: UITabBar!
    @IBOutlet weak var lfPromoPrice: UILabel!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var imageScrollView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    
    var barcodeInfo = WSBarcodeInfo()
    var cartItem = ShoppingCartItem()
    var btnBarBadge : MJBadgeBarButton!
    
    var delegate: IProductSelectorListener!
    
    var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
    var images: [UIImage] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.delegate = self

        self.initData()
        self.initProductAttributes()
    }
    
    func createImageSlideShow(){
        imageScrollView.delegate = self
        self.contentView.addSubview(imageScrollView)
        
        for index in 0..<images.count {
            
            frame.origin.x = self.imageScrollView.frame.size.width * CGFloat(index)
            frame.size = self.imageScrollView.frame.size
            self.imageScrollView.isPagingEnabled = true
            
            let imgView = UIImageView(frame: frame)
            imgView.contentMode = UIView.ContentMode.scaleAspectFit
            imgView.image = images[index]
            self.imageScrollView.addSubview(imgView)
        }
        
        self.imageScrollView.contentSize = CGSize(width:self.imageScrollView.frame.size.width * CGFloat(images.count),height: self.imageScrollView.frame.size.height)
        pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControl.Event.valueChanged)
    }
    
    func initData(){
        if delegate.isbagButtonVisible() {
            self.createShoppingBagButtonBadge()
        }
        
        self.tabBar.isHidden = !delegate.isTabBarVisible()

        self.barcodeInfo = cartItem.barcodeInfo
        
        State.LoadProductImages(productId: self.barcodeInfo.ProductId) { result in
            if result {
                if(State.productImages.count > 0){
                    for productImage in State.productImages{
                        if productImage.ProductImage != nil {
                            self.images.append(productImage.ProductImage!)
                        }
                    }
                }
                else if self.barcodeInfo.ImageIcon != nil{
                    self.images.append(self.barcodeInfo.ImageIcon!)
                }
                else{
                    self.images.append(UIImage(named: "defaultProduct.png")!)
                }
            }
            else{
                self.images.append(UIImage(named: "defaultProduct.png")!)
            }
            self.createImageSlideShow()
            self.configurePageControl()
        }
        
        self.lfName.text = barcodeInfo.Name
        self.lfCode.text = barcodeInfo.Code
        
        self.lfColor.text = barcodeInfo.ColorName
        self.tabBar.items?[0].title = barcodeInfo.ColorName
        
        self.lfSize.text = barcodeInfo.SizeCode
        self.tabBar.items?[1].title =  barcodeInfo.SizeCode
        
        let netRowValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(cartItem.NetRowValue)
        let grossUnitValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(cartItem.GrossUnitValue)
        
        if(netRowValue.isLess(than: grossUnitValue)){
            self.lfPromoPrice.isHidden = false
            self.lfPromoPrice.textColor = UIColor.red
            self.lfPromoPrice.text = Util.DoubleToString(cartItem.NetRowValue) + " " + settings.userSettings.defaultCurrency
            let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToString(cartItem.GrossUnitValue) + " " + settings.userSettings.defaultCurrency)
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
            lfPrice.attributedText = attributeString
        }
        else{
            self.lfPromoPrice.isHidden = true
            self.lfPrice.text = Util.DoubleToString(cartItem.GrossUnitValue) + " " + settings.userSettings.defaultCurrency
        }
        
        self.lfBarcode.text = barcodeInfo.Barcode
        
        if(barcodeInfo.AvailableStockQuantity! > 0){
            self.lfStock.text = Util.getString("Stock") + ": " + (barcodeInfo.AvailableStockQuantity?.description)!
            //self.tabBar.items?[2].isEnabled = true
        }
        else {
            self.lfStock.text = Util.getString("Out of stock")
            //self.tabBar.items?[2].isEnabled = false
        }
        self.tvDescription.text = barcodeInfo.Description
        
        self.tabBar.items?[2].title = delegate.addButtonText()
    }
    
    func initProductAttributes(){
        State.LoadStylesView(productId: self.barcodeInfo.ProductId, completionHandler: {   })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.title = Util.getString("Details")
        
        if delegate.isbagButtonVisible(){
            self.btnBarBadge.badgeValue = delegate.productAddedCount().description
        }
    }
    
    @objc func viewShoppingBag(_ sender: Any){
        var vc: UIViewController? = nil
        if let nc = self.navigationController {
            for i in 0..<nc.viewControllers.count{
                if (nc.viewControllers[i].isKind(of: ShoppingCartViewController.self)){
                    if  let viewController = self.navigationController?.viewControllers[i]{
                        vc = viewController
                        break
                    }
                }
            }
        }
        
        if let shoppingCartViewController = vc{
            _ = self.navigationController?.popToViewController(shoppingCartViewController, animated: false)
        }
        else{
            self.instantiateNewShoppingCart()
        }
    }
    
    func instantiateNewShoppingCart(){
        let shoppingCartViewController = AppDelegate.leftViewController.shoppingCartView!
        shoppingCartViewController.isSlideButtonEnabled = false
        self.navigationController?.pushViewController(shoppingCartViewController, animated: true)
    }
    
    func createShoppingBagButtonBadge(){
        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
        
        self.navigationItem.rightBarButtonItem = btnBarBadge
    }
    
    func getDistinctColors() -> ([ProductAttribute]) {
        var distinctColors = [ProductAttribute]()
        
        for style in State.styleView {
            if style.Barcode != nil {
                if !distinctColors.contains(where: { $0.id == style.ColorId }) {
                    let color = ProductAttribute(id: style.ColorId!,name: style.ColorName!)
                    distinctColors.append(color)
                }
            }
        }
        return distinctColors
    }
    
    func getDistinctSizes() -> ([ProductAttribute]) {
        var distinctSizes = [ProductAttribute]()
        
        for style in State.styleView {
            if style.Barcode != nil{
                if ( (style.ColorName == self.barcodeInfo.ColorName) && (!distinctSizes.contains(where: {$0.id == style.SizeId } )))  {
                    let size = ProductAttribute(id: style.SizeId!,name: style.SizeCode!)
                    distinctSizes.append(size)
                }
            }
        }
        return distinctSizes
    }
    
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if(item.tag == 0) {
            self.openSelector(dataSource: getDistinctColors(), tabBarItem: item)
        }
        else if(item.tag == 1){
            self.openSelector(dataSource: getDistinctSizes(), tabBarItem: item)
        }
        else if(item.tag == 2) {
            if(self.barcodeInfo.SizeCode == nil){
                self.openSelector(dataSource: getDistinctSizes(), tabBarItem: self.tabBar.items![1])
            }
            else{
                if self.barcodeInfo.hasSerialNumber {
                    self.alertAddProductSN(barcodeInfo: barcodeInfo)
                }
                else if barcodeInfo.IsPriceChangeRequired == true{
                    self.alertPriceChangeRequired(barcodeInfo: barcodeInfo, viewController: self)
                }
                else if let decimalPlaces = barcodeInfo.DecimalPlaces, decimalPlaces > 0 {
                    self.alertChangeQuantityRequired(decimalPlaces: decimalPlaces)
                }
                else{
                    self.delegate.productSelected(barcodeInfo: self.barcodeInfo, viewController: self)
                    Util.writeLogAddToCart(price: NSDecimalNumber(value: self.barcodeInfo.SalePrice), currency: settings.userSettings.currencyId, itemName: self.barcodeInfo.Name, itemType: self.barcodeInfo.Code, itemId: self.barcodeInfo.ProductId, customAttribute: ["StoreId":"\(settings.StoreId)", "CashRegister":"\(settings.CashRegister)"])
                    if self.delegate.isbagButtonVisible(){
                        self.btnBarBadge.badgeValue = self.delegate.productAddedCount().description
                    }
                }
            }
        }
    }
    
    func alertPriceChangeRequired(barcodeInfo: WSBarcodeInfo, viewController: UIViewController){
        self.simpleAlertWithTextEdit(title: barcodeInfo.Name, message: Util.getString("InsertNewPrice"), text: "", UIViewController: self, actionOk: { value in
            self.barcodeInfo.SalePrice = Double(value ?? "0.00") ?? 0
            
            if let decimalPlaces = barcodeInfo.DecimalPlaces, decimalPlaces > 0 {
                self.alertChangeQuantityRequired(decimalPlaces: decimalPlaces)
            }
            else{
                self.delegate.productSelected(barcodeInfo: self.barcodeInfo, viewController: self)
                if self.delegate.isbagButtonVisible(){
                    self.btnBarBadge.badgeValue = self.delegate.productAddedCount().description
                }
            }
        }) {
            return
        }
    }
    
    var alertPriceChange = UIAlertController()
    func simpleAlertWithTextEdit(title: String, message:String, text: String?, UIViewController: UIViewController, actionOk: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))   {
        self.alertPriceChange = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        self.alertPriceChange.addTextField { textField in
            textField.text = text
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingDidBegin)
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
            textField.keyboardType = .numbersAndPunctuation
        }
        
        self.alertPriceChange.addAction(UIAlertAction(title: Util.getString("Ok"), style: .default, handler: {(_) in
            actionOk(self.alertPriceChange.textFields?[0].text)
        }))
        
        self.alertPriceChange.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        UIViewController.present(self.alertPriceChange, animated: true, completion: {
        })
    }
    
    @objc func textChanged(_ textField: UITextField) {
        self.alertPriceChange.actions[0].isEnabled = false
        if let text = textField.text{
            if text.isEmpty == false {
                if  Util.isTextDoubleValue(value: text) {
                    self.alertPriceChange.actions[0].isEnabled = true
                }
                else{
                    self.alertPriceChange.actions[0].isEnabled = false
                }
            }
            else{
                self.alertPriceChange.actions[0].isEnabled = false
            }
        }
    }
    
    func alertAddProductSN(barcodeInfo: WSBarcodeInfo){
        Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("InsertSN"), UIViewController: self, actionYes: { text in
            self.addNewObjectAsTextCallback(text: text!, barcodeInfo: barcodeInfo)
        }) {
            return
        }
    }
    
    func addNewObjectAsTextCallback(text: String, barcodeInfo: WSBarcodeInfo){
        if text == ""{
            self.alertAddProductSN(barcodeInfo: barcodeInfo)
        }
        else{
            self.barcodeInfo.serialNumber = text
            self.delegate.productSelected(barcodeInfo: self.barcodeInfo, viewController: self)
            if delegate.isbagButtonVisible(){
                self.btnBarBadge.badgeValue = delegate.productAddedCount().description
            }
        }
    }
    
    func alertChangeQuantityRequired(decimalPlaces: Int){
        self.simpleAlertChangeQuantity(title: self.barcodeInfo.Name, message: Util.getString("InsertNewQuantity"), decimalPlaces: decimalPlaces, actionOk: { value in
            
            if let quantityString = value, let quantity = Double(quantityString){
                self.barcodeInfo.quantity = quantity
            }
            else{
                let quantityString = Util.DoubleToStringQuantity(1, decimalPlaces: decimalPlaces)
                let quantity: Double = Double(quantityString) ?? 1
                
                self.barcodeInfo.quantity = quantity
            }
            
            self.delegate.productSelected(barcodeInfo: self.barcodeInfo, viewController: self)
            if self.delegate.isbagButtonVisible(){
                self.btnBarBadge.badgeValue = self.delegate.productAddedCount().description
            }
        }) {
            return
        }
    }
        
    var alertChangeQuantity = UIAlertController()
    func simpleAlertChangeQuantity(title: String, message: String, decimalPlaces: Int, actionOk: @escaping ((String?) -> ()), actionNo: @escaping (() -> ())) {
        self.alertChangeQuantity = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        self.alertChangeQuantity.addTextField { textField in
            textField.text = Util.DoubleToStringQuantity(1, decimalPlaces: decimalPlaces)
            textField.quantityDecimalPlaces = decimalPlaces
            textField.addTarget(self, action: #selector(self.quantityChanged(_:)), for: .editingDidBegin)
            textField.addTarget(self, action: #selector(self.quantityChanged(_:)), for: .editingChanged)
            textField.keyboardType = .numbersAndPunctuation
            
            let placeholder = Util.DoubleToStringQuantity(1, decimalPlaces: decimalPlaces)
            let height = textField.frame.height
            let size: CGSize = placeholder.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)])
            
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: height))
            label.textAlignment = NSTextAlignment.right
            label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
            label.text = placeholder
            textField.placeholder = nil
            textField.rightView = label
            textField.rightViewMode = .always
        }
        
        self.alertChangeQuantity.addAction(UIAlertAction(title: Util.getString("Ok"), style: .default, handler: {(_) in
            actionOk(self.alertChangeQuantity.textFields?[0].text)
        }))
        
        self.alertChangeQuantity.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        self.present(self.alertChangeQuantity, animated: true, completion: {
            self.alertChangeQuantity.textFields?[0].selectAll(self.alertChangeQuantity)
        })
    }
    
    @objc func quantityChanged(_ textField: UITextField) {
        self.alertChangeQuantity.actions[0].isEnabled = false
        if let text = textField.text{
            if text.isEmpty == false {
                if Util.isTextDoubleValue(text: text, decimalPlaces: textField.quantityDecimalPlaces) {
                    if Double(text) != 0 {
                        self.alertChangeQuantity.actions[0].isEnabled = true
                    }
                    else{
                        self.alertChangeQuantity.actions[0].isEnabled = false
                    }
                }
                else{
                    self.alertChangeQuantity.actions[0].isEnabled = false
                }
            }
            else{
                self.alertChangeQuantity.actions[0].isEnabled = false
            }
        }
    }

    func openSelector(dataSource: [ProductAttribute], tabBarItem: UITabBarItem ){
        let popupSelectorViewController =  self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.preferredContentSize = CGSize(width: 200, height: 200)
        popupSelectorViewController.itemSelectedCallback = selectedProductAttribute
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.parentItem = tabBarItem
        
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.popover
        let popover = nav.popoverPresentationController
        popover?.delegate = self
        popover?.sourceView = self.tabBar
        let tabBarItemWidth = Int(self.tabBar.frame.size.width) / (self.tabBar.items?.count)!
        let xPossition = tabBarItemWidth / 2 + (tabBarItem.tag * tabBarItemWidth)
        popover?.sourceRect = CGRect(x: xPossition, y: 0, width: 0, height: 0)
        
        self.present(nav, animated: true, completion: nil)
    }
    
    func selectedProductAttribute(item: AnyObject, tabBarItem: AnyObject?){
        let selectedProductAttribute = item as! ProductAttribute
        let tabBarItem = tabBarItem as! UITabBarItem
        if(tabBarItem.tag == 0){
            self.setColorName(selectedProductAttribute.name)
            self.setSizeCode(nil)
        }
        else if(tabBarItem.tag == 1){
            self.setSizeCode(selectedProductAttribute.name)
        }
    }
    
    func setColorName(_ colorName: String) {
        self.lfColor.text = colorName
        self.tabBar.items?[0].title = colorName
        self.barcodeInfo.ColorName = colorName
    }
    
    func setSizeCode(_ sizeCode: String?) {
        self.lfSize.text = sizeCode
        self.tabBar.items?[1].title = sizeCode
        self.barcodeInfo.SizeCode = sizeCode
        self.barcodeInfo.StyleId = getStyle(colorName: self.barcodeInfo.ColorName!, sizeCode: sizeCode)?.StyleId
        self.barcodeInfo.Barcode = getStyle(colorName: self.barcodeInfo.ColorName!, sizeCode: sizeCode)?.Barcode
        self.lfBarcode.text = self.barcodeInfo.Barcode
        if let availableStock = getStyle(colorName: self.barcodeInfo.ColorName!, sizeCode: sizeCode)?.AvailableStockQuantity {
            if(availableStock > 0){
                self.lfStock.text = Util.getString("Stock") + ": \(availableStock)"
            }
            else {
                self.lfStock.text = Util.getString("Out of stock")
            }
        }
        else{
            self.lfStock.text = ""
        }
    }
    
    func getStyle(colorName: String, sizeCode: String?) -> WSStyleView? {
        for style in State.styleView {
            if style.ColorName == colorName && style.SizeCode == sizeCode {
                return style
            }
        }
        return nil
    }
    
    func configurePageControl() {
        if self.images.count > 1 {
            self.pageControl.numberOfPages = self.images.count
            self.pageControl.currentPage = 0
            self.pageControl.pageIndicatorTintColor = UIColor.gray
            self.pageControl.currentPageIndicatorTintColor = UIColor.black
            self.contentView.addSubview(self.pageControl)
        }
        
    }
    
    @objc func changePage(sender: AnyObject) -> () {
        let x = CGFloat(pageControl.currentPage) * imageScrollView.frame.size.width
        self.imageScrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        self.pageControl.currentPage = Int(pageNumber)
    }
}
