UnifiedCouponBarcodeViewController.swift 12.2 KB
//
//  UnifiedCouponBarcodeViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 6/4/23.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation
import SwiftEventBus

@objc public class UnifiedCouponBarcodeViewController: UIViewController {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var tableView: UITableView!
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    var termsVisible: Bool = false;
    var barcodeVisible: Bool = false;
    var couponsVisible: Bool = false;

    var mapBtnVisible: Bool = false;
    var eshopBtnVisible: Bool = false;
    var eshopWebsite: String = "";
    
    public var coupon: swiftApi.UnifiedCouponModel?
    public var isFromWallet: Bool? = false
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true
        
        tableView.delegate = self
        tableView.dataSource = self

        // Do any additional setup after loading the view.
        setBackButton()
        setNavigationTitle("Εκπτωτικό κουπόνι")

        // Logs
//        print("Coupon: " + (coupon?.coupon ?? ""))
//        print("Coupon Name: " + (couponSetData?.name ?? ""))
//        print("Coupon Description: " + (couponSetData?.short_description ?? ""))
//        print("Coupon Expiration: " + (coupon?.expiration ?? ""))
        
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "UnifiedCouponScreen")
        
        self.navigationController?.hideHairline()
    }
    
    
    // MARK: - Functions
    func showConfirmDialog() -> Void {

        let alert = UIAlertController(title: "Ακύρωση Κουπονιού", message: "Είσαι σίγουρος ότι θέλεις να ακυρώσεις το κουπόνι σου;", preferredStyle: .alert)

        let cancelButton = UIAlertAction(title: "Όχι", style: .default, handler: { action in
            switch action.style{
                case .default:
                print("default")

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

            }
        })
        // cancelButton.setValue(UIColor(rgb: 0xFC5757), forKey: "titleTextColor")
        alert.addAction(cancelButton)

        alert.addAction(UIAlertAction(title: "Ναι", style: .default, handler: { action in
            switch action.style{
                case .default:
                self.cancelUnifiedCouponRequest()

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

            }
        }))
        
        self.present(alert, animated: true, completion: nil)
    }

    func showSuccessDialog() -> Void {

        let alert = UIAlertController(title: "Ακύρωση Κουπονιού", message: "Το ενιαίο κουπόνι σου ακυρώθηκε επιτυχώς. Βρες τα μεμονωμένα κουπόνια στο καλάθι SUPERMARKET DEALS.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
            switch action.style{
                case .default:
                SwiftEventBus.post("refresh_unified_coupons")
                self.navigationController?.popViewController(animated: true)
                // self.dismiss(animated: true, completion: {})

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

            }
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    func cancelUnifiedCouponRequest () -> Void {
        var tranIdFound = "";
        for coupon in self.coupon?._coupons ?? [] {
            if ((coupon.transaction_uuid != nil) && coupon.transaction_uuid != "") {
                tranIdFound = coupon.transaction_uuid ?? "";
                break;
            }
        }
        
        if (tranIdFound != "") {
            swiftApi().cancelUnifiedCouponAsync(transactionId: tranIdFound, self.cancelUnifiedCouponCallback, failureCallback: { errorCode in })
        }
    }
    
    func cancelUnifiedCouponCallback (_ responseData: swiftApi.GenericResponseModel?) -> Void {
        if (responseData != nil) {
            DispatchQueue.main.async {
                if (responseData?.getStatus == 1) {
                    self.showSuccessDialog()
                }
                
            }
        }
    }
    
    // MARK: - Actions
    @IBAction func showCouponsButtonAction(_ sender: Any) {
        couponsVisible = !couponsVisible
//        self.tableView.reloadSections(IndexSet(0..<2), with: .none)
        self.tableView.reloadData()
    }
    
    @IBAction func showBarcodeAction(_ sender: Any) {
        barcodeVisible = !barcodeVisible
//        self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
        self.tableView.reloadData()
    }
    
    @IBAction func termsButtonAction(_ sender: Any) {
        termsVisible = !termsVisible
//        self.tableView.reloadSections(IndexSet(integer: 2), with: .none)
        self.tableView.reloadData()
    }

    @IBAction func mapButtonAction(_ sender: Any) {
        swiftApi().logTrackersEvent("click", "SeeShops")
//
        let vc = SwiftWarplyFramework.MapsViewController(nibName: "MapsViewController", bundle: Bundle(for: MyEmptyClass.self))
//        vc.couponSet = coupon?.couponset_data
        vc.isMarket = true
        self.navigationController?.pushViewController(vc, animated: true)

        // if (mapBtnVisible == true) {
        //     swiftApi().logTrackersEvent("click", "SeeShops")
            
        //     let vc = SwiftWarplyFramework.MapsViewController(nibName: "MapsViewController", bundle: Bundle(for: MyEmptyClass.self))
        //     vc.couponSet = coupon?.couponset_data
        //     self.navigationController?.pushViewController(vc, animated: true)

        // } else if (eshopBtnVisible == true) {
        //     if (eshopWebsite != "") {
        //         guard let websiteUrl = URL(string: eshopWebsite) else {
        //               print("Error creating URL")
        //               return
        //         }
                
        //         // check if link can be opened.
        //         guard UIApplication.shared.canOpenURL(websiteUrl) else {
        //             return
        //         }
                
        //         swiftApi().logTrackersEvent("click", "SeeShopWebsite")
        //         UIApplication.shared.open(websiteUrl, options: [:], completionHandler: nil)
        //     }
        // }
    }
    
    @IBAction func cancelButtonAction(_ sender: Any) {
        self.showConfirmDialog()
    }
}

// MARK: - TableView
extension UnifiedCouponBarcodeViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0) {
            return 1
        } else if (section == 1) {
            if (couponsVisible == true) {
                return self.coupon?._coupons.count ?? 0
            } else {
                return 0
            }
            
        } else if (section == 2) {
            return 1
        } else {
            return 0
        }

    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath.section == 0) {
            return UITableView.automaticDimension
        } else if (indexPath.section == 1) {
            if (couponsVisible == true) {
                return 130.0 + 8.0
            } else {
                return 0.0
            }
            
        } else if (indexPath.section == 2) {
            return UITableView.automaticDimension
        } else {
            return 0.0
        }
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UnifiedCouponBCHeaderTableViewCell", for: indexPath) as! UnifiedCouponBCHeaderTableViewCell
            
            cell.configureCell(coupon: self.coupon, couponsVisible: couponsVisible)
            
            return cell
            
        } else if (indexPath.section == 1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CouponsTableViewCellId", for: indexPath) as! CouponsTableViewCell
            
            cell.configureCell(coupon: (self.coupon?._coupons[indexPath.row])!, isMarket: true)
            
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UnifiedCouponBCFooterTableViewCell", for: indexPath) as! UnifiedCouponBCFooterTableViewCell
            
            cell.configureCell(termsVisible: termsVisible)
            
            return cell
        }
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // SwiftEventBus.post("couponBarcodePressed", sender: coupons[indexPath.row])
        
        // Logs
//        let couponSetData: swiftApi.CouponSetItemModel? = self.coupon?._coupons[indexPath.row].couponset_data
//        print("Coupon clicked: " + (self.coupon?._coupons[indexPath.row].coupon ?? ""))
//        print("Coupon Name clicked: " + (couponSetData?.name ?? ""))
//        print("Coupon Description clicked: " + (couponSetData?.short_description ?? ""))
//        print("Coupon Expiration clicked: " + (self.coupon?._coupons[indexPath.row].expiration ?? ""))
        
        if (indexPath.section == 1) {
            swiftApi().logTrackersEvent("click", ("Coupon:" + (self.coupon?._coupons[indexPath.row].name ?? "")))
            
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            let vc = storyboard.instantiateViewController(withIdentifier: "CouponBarcodeViewController") as! SwiftWarplyFramework.CouponBarcodeViewController
            vc.coupon = self.coupon?._coupons[indexPath.row]
            vc.isMarket = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if (section == 0){
            return nil
            
        } else if (section == 1) {
            if (couponsVisible == true) {
                let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 12))
                 view.backgroundColor =  UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.00)

                return view
            } else {
                return nil
            }
            
        } else {
            return nil
        }
    }

    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if (section == 0) {
            return 0.0
            
        } else if (section == 1) {
            if (couponsVisible == true) {
                return 12.0
            } else {
                return 0.0
            }
            
        } else {
            return 0.0
        }
    }

    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if (section == 0) {
            return 0.0
            
        } else if (section == 1) {
            if (couponsVisible == true) {
                return 2.0
            } else {
                return 0.0
            }
            
        } else {
            return 0.0
        }
    }

    public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if (section == 0){
            return nil
            
        } else if (section == 1) {
            if (couponsVisible == true) {
                let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 2))
                 view.backgroundColor =  UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.00)

                return view
            } else {
                return nil
            }
            
        } else {
            return nil
        }
    }
    
}