//
//  MyWalletController.swift
//  Dealfly
//
//  Created by Amine maagoul on 16/8/2023.
//  Copyright © 2023 Amine. All rights reserved.
//


import UIKit
import Atributika
import ImageSlideshow
import AssistantKit
import SwiftWebVC
import SwiftEventBus


class MyWalletController: MyUIViewController, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, WTransactionDelegate, NavigatorDelegate {
    func onClosed() {
        load()
    }
    
    
    //RESULT
    var GLOBAL_COUNT: Int = 0
    var LIST: [WTransaction] = [WTransaction]()
    var __req_page: Int = 1
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    
    @IBOutlet weak var walletHeaderHolder: UIView!
    @IBOutlet weak var yourBalanceLabel: UILabel!
    @IBOutlet weak var balanceAmountValue: UILabel!
    @IBOutlet weak var topupBtn: UIButton!
    @IBOutlet weak var sendMoneyBtn: UIButton!
    @IBOutlet weak var withdrawBtn: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var lastActivityLabel: UILabel!
    
    @IBAction func topUpAction(_ sender: Any) {
        if let url = topUpUrl{
            startNavigator(url: url)
        }
    }
    
    @IBAction func sendMoneyAction(_ sender: Any) {
        if let url = sendMoneyUrl{
            startNavigator(url: url)
        }
    }
    
    @IBAction func withdrawAction(_ sender: Any) {
        if let url = withdrawUrl{
            startNavigator(url: url)
        }
    }
    
    var sendMoneyUrl: String?
    var withdrawUrl: String?
    var topUpUrl: String?
    var balance: String?
    
    override func viewDidLoad() {
        
        setupNavBarTitles()
        setupNavBarButtons()
        
        setup()
        
    }
    
    var cellId = "wTransactionCellId"

    
    func setup()  {
        
        
        self.sendMoneyBtn.setCustomButtonControlStyle()
        self.withdrawBtn.setCustomButtonControlStyle(active: true)
        
        self.lastActivityLabel.initBolodFont()
        self.topupBtn.initDefaultFont()
        self.sendMoneyBtn.initDefaultFont()
        self.withdrawBtn.initDefaultFont()
        self.balanceAmountValue.initBolodFont(size: 22)
        self.yourBalanceLabel.initDefaultFont()
        self.walletHeaderHolder.backgroundColor = Colors.primaryColor
        
        self.yourBalanceLabel.text = "Your balance".localized
        self.balanceAmountValue.text = "0.0$"
        self.topupBtn.setTitle("+Top-up".localized, for: .normal)
        self.lastActivityLabel.text = "Last activity".localized
        self.topupBtn.setTitleColor(.white, for: .normal)
        self.topupBtn.isHidden = true
        
        
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.scrollDirection = .vertical
            flowLayout.minimumLineSpacing = 0
            
            
            flowLayout.itemSize = CGSize(width: collectionView.frame.width , height: 80)
            flowLayout.minimumInteritemSpacing = 0
            flowLayout.minimumLineSpacing = 5
            
            self.view.layoutIfNeeded()
        }
     
        
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
    
        collectionView.backgroundColor = .clear
        collectionView.isScrollEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        

        collectionView.register(UINib(nibName: "TransactionCell", bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        load()
     
    }
    
    override func viewDidAppear(_ animated: Bool) {
    
    }
    
    
    
    func setupFields(parser: Parser){
       /*
        try {
                  myBalance.setText(parser.getBalance());
              } catch (JSONException e) {
                  myBalance.setText("0.0");
              }

              try {
                  sendMoneyUrl = parser.getField("sendMoneyUrl");
              } catch (JSONException e) {
                  sendMoneyUrl = null;
              }

              try {
                  withdrawUrl = parser.getField("withdrawUrl");
              } catch (JSONException e) {
                  withdrawUrl = null;
              }

              try {
                  topUpUrl = parser.getField("topUpUrl");
              } catch (JSONException e) {
                  topUpUrl = null;
              }
        */
    }
    
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles() {
        
        
        let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
        topBarTitle.frame = rect
        topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
        
        topBarTitle.text = "My wallet".localized
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: color)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
   
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
                    -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TransactionCell

        cell.setupSettings()
        cell.setup(object: LIST[indexPath.item])


        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


    }
    

    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LIST.count
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

      
    
       
        
    }
    
    


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: CGFloat(80))
        
        
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        if Device.isPad {

            if Device.screen == .inches_9_7 {
                return UIEdgeInsets(top: 10, left: 6, bottom: 0, right: 6)
            } else {
                return UIEdgeInsets(top: 20, left: 6, bottom: 0, right: 6)
            }

        } else {
            return UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        }
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

        //item = 10, count = 10 , COUNT = 23

        Utils.printDebug(" Paginate \((indexPath.item + 1)) - \(LIST.count) - \(GLOBAL_COUNT)")

        if indexPath.item + 1 == LIST.count && LIST.count < GLOBAL_COUNT && !isLoading {
            Utils.printDebug(" Paginate! \(__req_page) ")
            self.load()
        }

    }
    
    private var isLoading = false
    
    
    
    //API

    var wtransactionLoader: WTransactionLoader = WTransactionLoader()

    func load() {


        self.wtransactionLoader.delegate = self

        //Get current Location

        var parameters = [
            "limit": "50"
        ]
        
        if Session.isLogged(), let sess = Session.getInstance(){
            parameters["user_id"] = String(sess.user!.id)
        }

        MyProgress.show()
        
        self.isLoading = true
        self.wtransactionLoader.load(url: Constances.Api.API_DIGITAL_WALLET, parameters: parameters)

    }


    func success(parser: WTransactionParser, response: String) {

        MyProgress.dismiss()

        if parser.success == 1 {
            
            balance = parser.json!["balance"].stringValue
            sendMoneyUrl = parser.json!["sendMoneyUrl"].stringValue
            topUpUrl = parser.json!["topUpUrl"].stringValue
            withdrawUrl = parser.json!["withdrawUrl"].stringValue
            
            
            self.balanceAmountValue.text = balance
            

            let transactions = parser.parse()

            self.GLOBAL_COUNT = parser.count

            if transactions.count > 0 {

                Utils.printDebug("We loaded \(transactions.count)")


                if self.__req_page == 1 {
                    self.LIST = transactions
                } else {
                    self.LIST += transactions
                }

                self.collectionView.reloadData()

                if self.LIST.count < self.GLOBAL_COUNT {
                    self.__req_page += 1
                }


            }

        }
        
        
        self.isLoading = false

    }
    
    func error(error: Error?, response: String) {
        
        MyProgress.dismiss()
        
        self.showAlert(title: "Error!".localized, content: ["err" : "Error from server side".localized], msgBnt: "OK".localized)
    }
    
    
    func startNavigator(url: String)  {
          
          let sb = UIStoryboard(name: "Navigator", bundle: nil)
          let ms: NavigatorController = sb.instantiateViewController(withIdentifier: "navigatorVC") as! NavigatorController
          
          ms.config.backHome = true
          ms.config.customToolbar = true
            ms.link = url
        ms.delegate = self
        
        ms.modalPresentationStyle = .fullScreen
          
          if let controller = self.navigationController{
              controller.pushViewController(ms, animated: true)
          }else{
               self.present(ms, animated: true)
          }
         
         
      }

}
