LoyaltyHistoryViewController.swift 16.7 KB
//
//  LoyaltyHistoryViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 25/10/23.
//

import Foundation
import UIKit
import SwiftEventBus

@objc public class LoyaltyHistoryViewController: UIViewController {
    @IBOutlet weak var sectionTitleLabel: UILabel!
    @IBOutlet weak var historySectionView: UIView!
    
    @IBOutlet weak var sumBadgeImage: UIImageView!
    @IBOutlet weak var sumBadgeLabel: UILabel!
    @IBOutlet weak var sumBannerLabel: UILabel!
    
    @IBOutlet weak var dfyBannerParentView: UIView!
    @IBOutlet weak var dfyBannerInnerParentView: UIView!
    @IBOutlet weak var dfyBannerInnerView: UIView!
    @IBOutlet weak var dfyBadgeImage: UIImageView!
    @IBOutlet weak var dfyBadgeLabel: UILabel!
    @IBOutlet weak var dfyBannerLabel: UILabel!
    
    @IBOutlet weak var marketBannerParentView: UIView!
    @IBOutlet weak var marketBannerInnerView: UIView!
    @IBOutlet weak var marketBadgeImage: UIImageView!
    @IBOutlet weak var marketBadgeLabel: UILabel!
    @IBOutlet weak var marketBannerLabel: UILabel!
    
    @IBOutlet weak var gfyBannerParentView: UIView!
    @IBOutlet weak var gfyBannerInnerView: UIView!
    @IBOutlet weak var couponBadgeImage: UIImageView!
    @IBOutlet weak var couponBadgeLabel: UILabel!
    @IBOutlet weak var gfyBannerLabel: UILabel!
    
    public var coupons:Array<swiftApi.CouponItemModel> = swiftApi().getCouponList()
    public var dfyCoupons:Array<swiftApi.ActiveDFYCouponModel> = swiftApi().getActiveDFYCoupons()
    public var unifiedCoupons:Array<swiftApi.UnifiedCouponModel> = []
    public var loyaltyBadge:swiftApi.LoyaltyBadgeModel = swiftApi().getLoyaltyBadge()
    
    var totalCouponValue = swiftApi().getDealsCouponsSum()
    var totalCouponDiscount = Float(round(100 * swiftApi().getLoyaltyBadge()._value) / 100)
    var unifiedCouponsDiscount:Float = 0.0
    
    
    public override func viewDidLoad() {
        super.viewDidLoad()

        self.hidesBottomBarWhenPushed = true
        
        SwiftEventBus.onBackgroundThread(self, name: "coupons_fetched") { result in

            DispatchQueue.main.async {
                self.coupons = swiftApi().getCouponList()
                self.totalCouponDiscount = Float(round(100 * swiftApi().getLoyaltyBadge()._value) / 100)
                self.loyaltyBadge = swiftApi().getLoyaltyBadge()
//                self.tableView.reloadData()
                self.updateUI()
            }
        }
        
        SwiftEventBus.onBackgroundThread(self, name: "unified_coupons_fetched") { result in

            DispatchQueue.main.async {
                self.unifiedCoupons = swiftApi().getUnifiedCouponList()
                
                self.matchOldSMCoupons()
                self.updateMarketBadge()
//                self.tableView.reloadData()
                self.updateUI()
            }
        }
        
        setBackButton()
        setNavigationTitle("Ιστορικό")
        
        // === images === //
        
        sumBadgeImage.image = UIImage(named: "history_heart", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        dfyBadgeImage.image = UIImage(named: "history_banner_dfy", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        marketBadgeImage.image = UIImage(named: "history_banner_sm", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        couponBadgeImage.image = UIImage(named: "history_banner_gfy", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        
        sectionTitleLabel.text = "Εξαργυρωμένα κουπόνια"
        
        historySectionView.backgroundColor = .white
        historySectionView.layer.cornerRadius = 16.0
        // historySectionView.layer.borderWidth = 1
        // historySectionView.layer.borderColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00).cgColor
        
        // Add shadow
        historySectionView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        historySectionView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        historySectionView.layer.shadowOpacity = 1.0
        historySectionView.layer.shadowRadius = 1.0
        
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "LoyaltyHistoryScreen")

        // addNavShadow()
        self.navigationController?.hideHairline()
        
        self.coupons = swiftApi().getCouponList()
        self.unifiedCoupons = swiftApi().getUnifiedCouponList()
        self.dfyCoupons = swiftApi().getActiveDFYCoupons()
        
        self.matchOldSMCoupons()
        self.updateMarketBadge()
//        self.tableView.reloadData()
        self.updateUI()
    }
    
//    public override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//
//        self.navigationController?.navigationBar.layer.shadowOpacity = 0.0
//        
//    }
    
    // MARK: - Functions
    func updateMarketBadge() {
        unifiedCouponsDiscount = 0.0
//        for smCouponSet in swiftApi().getCouponSetsDealsList() {
//            for oldCoupon in swiftApi().getAllOldCouponList() {
//                if (smCouponSet.uuid != "" && oldCoupon.couponset_uuid != "" && smCouponSet.uuid == oldCoupon.couponset_uuid) {
//
//                    oldCoupon.setCouponSetData(smCouponSet);
//
//                     if let discountFloat = Float(oldCoupon.discount ?? "0.0") {
//                         unifiedCouponsDiscount += discountFloat
//                     }
//                    break;
//                }
//            }
//        }
        
        for coupon in swiftApi().getOldUnifiedCouponList() {
            if let discountFloat = Float(coupon.discount ?? "0.0") {
                unifiedCouponsDiscount += discountFloat
            }
        }
        
        // TODO: UNCOMMENT if emptyView is needed again
//        if (totalCouponValue == 0.0 && loyaltyBadge._couponCount == 0 && dfyCoupons.count == 0 && coupons.count == 0 && unifiedCoupons.count == 0 && unifiedCouponsDiscount == 0.0) {
//            emptyView.isHidden = false
//            emptyViewHeight.constant = emptyView.intrinsicContentSize.height
//        } else {
//            emptyView.isHidden = true
//            emptyViewHeight.constant = 0
//        }
    }
    
    func matchOldSMCoupons() {
        var oldUnifiedCouponsArray:Array<swiftApi.CouponItemModel> = []
        
        for smCouponSet in swiftApi().getCouponSetsDealsList() {
            for oldCoupon in swiftApi().getAllOldCouponList() {
                if (smCouponSet.uuid != "" && oldCoupon.couponset_uuid != "" && smCouponSet.uuid == oldCoupon.couponset_uuid) {
                    
                    oldCoupon.setCouponSetData(smCouponSet);
                    oldUnifiedCouponsArray.append(oldCoupon);
                    
                    break;
                }
            }
        }
        
        oldUnifiedCouponsArray.sort(by: {
            let date1 = $0.redeemed_date
            let date2 = $1.redeemed_date
            
            if ((date1 != nil) && (date2 != nil)) {
                return date1!.compare(date2!) == .orderedDescending
            } else {
                return false
            }
            
        })
        swiftApi().setOldUnifiedCouponList(oldUnifiedCouponsArray)
    }
    
    func updateUI() {
        let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Regular", size: 14) ?? UIFont.systemFont(ofSize: 13), NSAttributedString.Key.foregroundColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)]
        let attrBold = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-SBold", size: 14) ?? UIFont.boldSystemFont(ofSize: 13), NSAttributedString.Key.foregroundColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)]
        
        // === SUM banner === //
        
        let sumRewards = totalCouponValue + totalCouponDiscount + unifiedCouponsDiscount
        
//        sumRewards = Float(round(100 * sumRewards) / 100)
        var sumRewardsString = "0"
        sumRewardsString = String(format: "%.2f", sumRewards).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
        sumBadgeLabel.text = sumRewardsString + "€"
        
        sumBannerLabel.text = "Δες αναλυτικά το συνολικό όφελός σου έως τώρα από κουπόνια"
        
        // === DFY banner === //
        
        dfyBannerParentView.backgroundColor = .clear
        dfyBannerInnerParentView.backgroundColor = .white
        dfyBannerInnerView.backgroundColor = UIColor(red: 0.46, green: 0.75, blue: 0.45, alpha: 0.05)
        dfyBannerInnerParentView.layer.cornerRadius = 16.0
        dfyBannerInnerView.layer.cornerRadius = 16.0
        // dfyBannerInnerView.layer.borderWidth = 1
        // dfyBannerInnerView.layer.borderColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00).cgColor
        
        dfyBannerParentView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        dfyBannerParentView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        dfyBannerParentView.layer.shadowOpacity = 1.0
        dfyBannerParentView.layer.shadowRadius = 1.0
        
        let totalCouponValueFixed = Float(round(100 * totalCouponValue) / 100)
        var totalCouponValueString = "0"
        totalCouponValueString = String(format: "%.2f", totalCouponValueFixed).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
        dfyBadgeLabel.text = totalCouponValueString + "€"
        
        let dfyNormalText1 = "Μέχρι τώρα έχεις όφελος "
        let dfyBoldText  = totalCouponValueString + "€"
        let dfyNormalText2 = " από τα DEALS FOR YOU"

        let dfyAttributedString = NSMutableAttributedString(string:dfyNormalText1, attributes:attrRegular)
        let dfyBoldString = NSMutableAttributedString(string: dfyBoldText, attributes:attrBold)
        let dfyNormalString = NSMutableAttributedString(string:dfyNormalText2, attributes:attrRegular)

        dfyAttributedString.append(dfyBoldString)
        dfyAttributedString.append(dfyNormalString)
        dfyBannerLabel.attributedText = dfyAttributedString
        
        // === MARKET banner === //
        
        marketBannerParentView.backgroundColor = .clear
        marketBannerInnerView.backgroundColor = UIColor(red: 1.00, green: 0.99, blue: 0.97, alpha: 1.00)
        marketBannerInnerView.layer.cornerRadius = 16.0
        // marketBannerInnerView.layer.borderWidth = 1
        // marketBannerInnerView.layer.borderColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00).cgColor
        
        marketBannerParentView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        marketBannerParentView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        marketBannerParentView.layer.shadowOpacity = 1.0
        marketBannerParentView.layer.shadowRadius = 1.0
        
        let marketDiscount = Float(round(100 * unifiedCouponsDiscount) / 100)
        var marketDiscountString = "0"
        marketDiscountString  = String(format: "%.2f", marketDiscount).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
    
        self.marketBadgeLabel.text = marketDiscountString + "€"
        
        let marketNormalText1 = "Μέχρι τώρα έχεις όφελος "
        let marketBoldText  = marketDiscountString + "€"
        let marketNormalText2 = " από τα SUPERMARKET DEALS!"

        let marketAttributedString = NSMutableAttributedString(string:marketNormalText1, attributes:attrRegular)
        let marketBoldString = NSMutableAttributedString(string: marketBoldText, attributes:attrBold)
        let marketNormalString = NSMutableAttributedString(string:marketNormalText2, attributes:attrRegular)

        marketAttributedString.append(marketBoldString)
        marketAttributedString.append(marketNormalString)
        marketBannerLabel.attributedText = marketAttributedString
        
        // === GFY banner === //
        
        gfyBannerParentView.backgroundColor = .clear
        gfyBannerInnerView.backgroundColor = UIColor(red: 0.96, green: 0.97, blue: 0.98, alpha: 1.00)
        gfyBannerInnerView.layer.cornerRadius = 16.0
        // gfyBannerInnerView.layer.borderWidth = 1
        // gfyBannerInnerView.layer.borderColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00).cgColor
        
        gfyBannerParentView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        gfyBannerParentView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        gfyBannerParentView.layer.shadowOpacity = 1.0
        gfyBannerParentView.layer.shadowRadius = 1.0
        
        var totalCouponDiscountString = "0"
        totalCouponDiscountString  = String(format: "%.2f", totalCouponDiscount).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
        couponBadgeLabel.text = totalCouponDiscountString + "€"
        
        let gfyNormalText1 = "Μέχρι τώρα έχεις όφελος "
        let gfyBoldText  = totalCouponDiscountString + "€"
        let gfyNormalText2 = " από τα GIFTS FOR YOU"

        let gfyAttributedString = NSMutableAttributedString(string:gfyNormalText1, attributes:attrRegular)
        let gfyBoldString = NSMutableAttributedString(string: gfyBoldText, attributes:attrBold)
        let gfyNormalString = NSMutableAttributedString(string:gfyNormalText2, attributes:attrRegular)

        gfyAttributedString.append(gfyBoldString)
        gfyAttributedString.append(gfyNormalString)
        gfyBannerLabel.attributedText = gfyAttributedString
    }
    
    // MARK: - Actions
    @IBAction func dfyBannerButtonAction(_ sender: Any) {
//        var totalCouponValue = swiftApi().getDealsCouponsSum()
//        if (totalCouponValue > 0.0) {
            print("DFY coupon banner pressed!")
           // analysis_pressed event
           let dealsAnalysis = swiftApi.WarplyDealsAnalysisEventModel()
           dealsAnalysis._isPressed = true
           SwiftEventBus.post("analysis_pressed", sender: dealsAnalysis)

//            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
//            firebaseEvent._eventName = "did_tap_gifts_for_you_badge"
//            firebaseEvent.setParameter = ("screen", "Loyalty History")
//            SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
            firebaseEvent._eventName = "did_tap_deals_for_you_badge"
            firebaseEvent.setParameter = ("screen", "Loyalty History")
            SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            swiftApi().logTrackersEvent("click", ("LoyaltyHistoryScreen:" + "DealsBanner"))
//        }
    }
    
    @IBAction func gfyBannerButtonAction(_ sender: Any) {
//        if (loyaltyBadge._couponCount > 0) {
//            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
//            firebaseEvent._eventName = "did_tap_deals_for_you_badge"
//            firebaseEvent.setParameter = ("screen", "Loyalty History")
//            SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
            firebaseEvent._eventName = "did_tap_gifts_for_you_badge"
            firebaseEvent.setParameter = ("screen", "Loyalty History")
            SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            swiftApi().logTrackersEvent("click", ("LoyaltyHistoryScreen:" + "LoyaltyBanner"))

            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            let vc = storyboard.instantiateViewController(withIdentifier: "LoyaltyAnalysisViewController") as! SwiftWarplyFramework.LoyaltyAnalysisViewController
            self.navigationController?.pushViewController(vc, animated: true)
//        }
    }
    
    @IBAction func marketBannerButtonAction(_ sender: Any) {
//        if (self.unifiedCouponsDiscount > 0.0) {
            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
            firebaseEvent._eventName = "did_tap_market_badge"
            firebaseEvent.setParameter = ("screen", "Loyalty History")
            SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            swiftApi().logTrackersEvent("click", ("LoyaltyHistoryScreen:" + "MarketBanner"))

            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            let vc = storyboard.instantiateViewController(withIdentifier: "MarketLoyaltyAnalysisViewController") as! SwiftWarplyFramework.MarketLoyaltyAnalysisViewController
            self.navigationController?.pushViewController(vc, animated: true)
//        }
    }
}