WalletViewController.swift 19.2 KB
//
//  WalletViewController.swift
//  WarplySDKFrameworkIOS
//
//  Created by Βασιλης Σκουρας on 5/5/22.
//

import Foundation
import UIKit
import SwiftEventBus

@objc public class WalletViewController: UIViewController {
    @IBOutlet weak var headerImage: UIImageView!
    @IBOutlet weak var profileImage: UIImageView!
    @IBOutlet weak var profileNameLabel: UILabel!
    @IBOutlet weak var questionnaireButton: UIButton!
    @IBOutlet weak var dfyEarnBannerView: UIView!
    @IBOutlet weak var dfyEarnBannerHeight: NSLayoutConstraint!
    @IBOutlet weak var dfyEarnBannerTopSpace: NSLayoutConstraint!
    @IBOutlet weak var dfyEarnLabel: UILabel!
    @IBOutlet weak var dfyEarnAmountLabel: UILabel!
    @IBOutlet weak var dfyEarnImage: UIImageView!
    @IBOutlet weak var couponEarnView: UIView!
    @IBOutlet weak var couponEarnViewHeight: NSLayoutConstraint!
    @IBOutlet weak var couponEarnViewTopSpace: NSLayoutConstraint!
    @IBOutlet weak var couponEarnLabel: UILabel!
    @IBOutlet weak var couponEarnAmountLabel: UILabel!
    @IBOutlet weak var couponEarnImage: UIImageView!
    @IBOutlet weak var dfyLogoImage: UIImageView!
    @IBOutlet weak var dfyLogoImageTopSpace: NSLayoutConstraint!
    @IBOutlet weak var dfyLogoImageHeight: NSLayoutConstraint!
    @IBOutlet weak var activeCodeView: UIView!
    @IBOutlet weak var activeCodeViewHeight: NSLayoutConstraint!
    @IBOutlet weak var activeCodesCountLabel: UILabel!
    @IBOutlet weak var activeCodeLabel: UILabel!
    @IBOutlet weak var activeCodeExpirationLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var activeCodeImage: UIImageView!
    @IBOutlet weak var myPresentsLabel: UILabel!
    @IBOutlet weak var emptyView: UIView!
    @IBOutlet weak var emptyImage: UIImageView!
    @IBOutlet weak var emptyLabel: UILabel!
    
    public var coupons:Array<swiftApi.CouponItemModel> = swiftApi().getCouponList()
    public var dfyCoupons:Array<swiftApi.ActiveDFYCouponModel> = swiftApi().getActiveDFYCoupons()
    public var loyaltyBadge:swiftApi.LoyaltyBadgeModel = swiftApi().getLoyaltyBadge()
    public var profile:swiftApi.ProfileModel? = swiftApi().getConsumer()
   
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true

        setBackButton()
        setNavigationTitle("For You")
        
        tableView.delegate = self
        tableView.dataSource = self

        print("Active Gifts Count: " + String(coupons.count))
        
       headerImage.image = UIImage(named: "ic_background_circle", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
       dfyEarnImage.image = UIImage(named: "wallet_dfy_earn", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
       couponEarnImage.image = UIImage(named: "wallet_coupons", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
       dfyLogoImage.image = UIImage(named: "dfy_logo_white", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
       activeCodeImage.image = UIImage(named: "active_code_logo", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        
        profileImage.layer.cornerRadius = 32.5
        profileImage.layer.borderWidth = 1
        profileImage.layer.borderColor = UIColor(red: 0.13, green: 0.66, blue: 0.71, alpha: 1.00).cgColor
        
        if (profile != nil && !(profile?._image_url is NSNull) && profile?._image_url != nil && profile?._image_url != "") {
            profileImage.load(link: profile?._image_url ?? "", placeholder: UIImage(), cache: URLCache())
        } else {
           profileImage.image = UIImage(named: "default_profile_image", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        }

        print("Profile Name: " + (profile?._firstname ?? "") + " " + (profile?._lastname ?? ""))

        profileNameLabel.text = (profile?._firstname ?? "") + " " + (profile?._lastname ?? "")
        
        let userTag = swiftApi().getUserTag()
        print("User tag: " + userTag)
        if (userTag != "" && userTag != "undefined") {
            questionnaireButton.setTitle(userTag, for: .normal)
            questionnaireButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 14)
            questionnaireButton.setTitleColor(.white, for: .normal)
    //        questionnaireButton.sizeToFit()
            questionnaireButton.frame = CGRect(x: 0.0, y: 0.0, width: questionnaireButton.intrinsicContentSize.width, height: questionnaireButton.intrinsicContentSize.height)
            questionnaireButton.applyGradient(colours: [UIColor(red: 0.40, green: 0.77, blue: 0.28, alpha: 1.00), UIColor(red: 0.10, green: 0.66, blue: 0.72, alpha: 1.00)], gradient: GradientOrientation.horizontal, cornerRadius: 7.0)
            // Shadow Color
            questionnaireButton.layer.shadowColor = UIColor(red: 0.33, green: 0.38, blue: 0.43, alpha: 1.00).cgColor
            questionnaireButton.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
            questionnaireButton.layer.shadowOpacity = 1.0
            questionnaireButton.layer.shadowRadius = 0.0
            questionnaireButton.layer.masksToBounds = false
        } else {
            questionnaireButton.setTitle("+Προτιμήσεις", for: .normal)
            questionnaireButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 14)
            questionnaireButton.setTitleColor(UIColor(red: 0.31, green: 0.62, blue: 0.18, alpha: 1.00), for: .normal)
            questionnaireButton.backgroundColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00)
            questionnaireButton.frame = CGRect(x: 0.0, y: 0.0, width: questionnaireButton.intrinsicContentSize.width, height: questionnaireButton.intrinsicContentSize.height)
        }
        
        questionnaireButton.layer.cornerRadius = 7.0
        
        dfyEarnBannerView.layer.cornerRadius = 5.0
        dfyEarnBannerView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.16).cgColor
        dfyEarnBannerView.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
        dfyEarnBannerView.layer.shadowOpacity = 1.0
        dfyEarnBannerView.layer.shadowRadius = 3.0
        
        var totalCouponValue = swiftApi().getDealsCouponsSum()

        if (totalCouponValue == 0.0) {
            dfyEarnBannerView.isHidden = true
            dfyEarnBannerHeight.constant = 0
            dfyEarnBannerTopSpace.constant = 0
        } else {
            dfyEarnBannerView.isHidden = false
            dfyEarnBannerHeight.constant = 75
            dfyEarnBannerTopSpace.constant = 30
        }

        totalCouponValue = Float(round(100 * totalCouponValue) / 100)
        var totalCouponValueString = "0"
        totalCouponValueString = String(format: "%.2f", totalCouponValue).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)

        // dfyEarnLabel.text = "Μέχρι τώρα έχεις κερδίσει " + totalCouponValueString + "€ με το DEALS for YOU!"

        let normalText1 = "Μέχρι τώρα έχεις κερδίσει "
        let boldText  = totalCouponValueString + "€"
        let normalText2 = " με το DEALS for YOU!"

        let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PFSquareSansPro-Regular", size: 17)]
        let attrBold = [NSAttributedString.Key.font : UIFont(name: "PFSquareSansPro-Bold", size: 17)]
        
        let attributedString = NSMutableAttributedString(string:normalText1, attributes:attrRegular)
        let boldString = NSMutableAttributedString(string: boldText, attributes:attrBold)
        let normalString = NSMutableAttributedString(string:normalText2, attributes:attrRegular)

        attributedString.append(boldString)
        attributedString.append(normalString)
        dfyEarnLabel.attributedText = attributedString
        
        dfyEarnAmountLabel.text = totalCouponValueString + "€"

        if (loyaltyBadge._couponCount == 0) {
            couponEarnView.isHidden = true
            couponEarnViewHeight.constant = 0
            couponEarnViewTopSpace.constant = 0
        } else {
            couponEarnView.isHidden = false
            couponEarnViewHeight.constant = 75
            couponEarnViewTopSpace.constant = 30
        }
        
        couponEarnView.layer.cornerRadius = 5.0
        couponEarnView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.16).cgColor
        couponEarnView.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
        couponEarnView.layer.shadowOpacity = 1.0
        couponEarnView.layer.shadowRadius = 3.0
        
        let totalCouponDiscount = Float(round(100 * loyaltyBadge._value) / 100)
        var totalCouponDiscountString = "0"
        totalCouponDiscountString  = String(format: "%.2f", totalCouponDiscount).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
        
        // couponEarnLabel.text = "Μέχρι τώρα έχεις κερδίσει " + totalCouponDiscountString + "€ σε προσφορές από " + String(loyaltyBadge._couponCount) + " κουπόνια!"

        let coupNormalText1 = "Μέχρι τώρα έχεις κερδίσει "
        let coupBoldText  = totalCouponDiscountString + "€"
        let coupNormalText2 = " σε προσφορές από "
        let coupBoldText2  = String(loyaltyBadge._couponCount)
        let coupNormalText3 = " κουπόνια!"

        let coupAttributedString = NSMutableAttributedString(string:coupNormalText1, attributes:attrRegular)
        let coupBoldString = NSMutableAttributedString(string: coupBoldText, attributes:attrBold)
        let coupNormalString2 = NSMutableAttributedString(string:coupNormalText2, attributes:attrRegular)
        let coupBoldString2 = NSMutableAttributedString(string: coupBoldText2, attributes:attrBold)
        let coupNormalString3 = NSMutableAttributedString(string:coupNormalText3, attributes:attrRegular)

        coupAttributedString.append(coupBoldString)
        coupAttributedString.append(coupNormalString2)
        coupAttributedString.append(coupBoldString2)
        coupAttributedString.append(coupNormalString3)
        couponEarnLabel.attributedText = coupAttributedString

        couponEarnAmountLabel.text = totalCouponDiscountString + "€"

        print("Loyalty Badge Value: " + totalCouponDiscountString)
        print("Loyalty Badge Count: " + String(loyaltyBadge._couponCount))
        
        activeCodeView.layer.cornerRadius = 5.0
        activeCodeView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.16).cgColor
        activeCodeView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
        activeCodeView.layer.shadowOpacity = 1.0
        activeCodeView.layer.shadowRadius = 6.0
        
        if (dfyCoupons.count > 0) {
            if (dfyCoupons.count == 1) {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
                
                // sort dfyCoupons by date
                dfyCoupons.sort(by: {
                    let date1 = dateFormatter.date(from: $0._date)
                    let date2 = dateFormatter.date(from: $1._date)
                    
                    if ((date1 != nil) && (date2 != nil)) {
                        return date1!.compare(date2!) == .orderedAscending
                    } else {
                        return false
                    }
                    
                })
                
                // Get days from now of the most recet coupon
                var daysFromNow = ""
                let calendar = Calendar.current

                // Replace the hour (time) of both dates with 00:00
                let date1 = calendar.startOfDay(for: Date())
                if let date2 = dateFormatter.date(from: dfyCoupons[0]._date) {
                    let components = calendar.dateComponents([.day], from: date1, to: date2)
                    daysFromNow = (components.day) != nil ? String(components.day ?? 0) : ""
                }
                
                activeCodesCountLabel.text = "Ενεργός κωδικός:"
                activeCodeLabel.text = dfyCoupons[0]._code
                // TODO: UNHIDE IT
                activeCodeExpirationLabel.isHidden = true
                if (daysFromNow == "1") {
                    activeCodeExpirationLabel.text = "Λήγει σε " + daysFromNow + " ημέρα"
                } else {
                    activeCodeExpirationLabel.text = "Λήγει σε " + daysFromNow + " ημέρες"
                }
                
            } else {
                var couponCodesString = ""
                for (index, item) in dfyCoupons.enumerated() {
                    if (index == (dfyCoupons.endIndex - 1)) {
                        couponCodesString += String(item._code)
                    } else {
                        couponCodesString += String(item._code) + ", "
                    }
                    
                }
                
                activeCodesCountLabel.text = String(dfyCoupons.count) + " Ενεργοί κωδικοί:"
                activeCodeLabel.text = couponCodesString
                activeCodeExpirationLabel.isHidden = true
            }
        } else {
            activeCodeLabel.text = "-"
            activeCodeExpirationLabel.text = ""

            dfyLogoImage.isHidden = true
            activeCodeView.isHidden = true
            
            dfyLogoImageHeight.constant = 0
            activeCodeViewHeight.constant = 0
            dfyLogoImageTopSpace.constant = 0
        }

        print("======= 1 =======")
        
        myPresentsLabel.text = "Τα δώρα μου"
        if (coupons.count > 0) {
            myPresentsLabel.isHidden = false
        } else {
            myPresentsLabel.isHidden = true
        }

        emptyImage.image = UIImage(named: "ic_empty_wallet", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        emptyLabel.text = "Δεν έχεις κάποιον ενεργό κωδικό ή κουπόνι! Μπες τώρα στην ενότητα COSMOTE For YOU και βρες αποκλειστικές προσφορές!"
        if (totalCouponValue == 0.0 && loyaltyBadge._couponCount == 0 && dfyCoupons.count == 0 && coupons.count == 0) {
            emptyView.isHidden = false
        } else {
            emptyView.isHidden = true
        }

        print("======= 2 =======")
    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let userTag = swiftApi().getUserTag()
        if (questionnaireButton.currentTitle != userTag) {
            if (userTag != "" && userTag != "undefined") {
                questionnaireButton.setTitle(userTag, for: .normal)
                questionnaireButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 14)
                questionnaireButton.setTitleColor(.white, for: .normal)
        //        questionnaireButton.sizeToFit()
                questionnaireButton.frame = CGRect(x: 0.0, y: 0.0, width: questionnaireButton.intrinsicContentSize.width, height: questionnaireButton.intrinsicContentSize.height)
                questionnaireButton.applyGradient(colours: [UIColor(red: 0.40, green: 0.77, blue: 0.28, alpha: 1.00), UIColor(red: 0.10, green: 0.66, blue: 0.72, alpha: 1.00)], gradient: GradientOrientation.horizontal, cornerRadius: 7.0)
                // Shadow Color
                questionnaireButton.layer.shadowColor = UIColor(red: 0.33, green: 0.38, blue: 0.43, alpha: 1.00).cgColor
                questionnaireButton.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
                questionnaireButton.layer.shadowOpacity = 1.0
                questionnaireButton.layer.shadowRadius = 0.0
                questionnaireButton.layer.masksToBounds = false
            } else {
                for layer in (questionnaireButton.layer.sublayers ?? []) {
                    if(layer.name == "linearGradientLayer"){
                        layer.removeFromSuperlayer()
                    }
                }
                questionnaireButton.layer.shadowOpacity = 0.0;
                questionnaireButton.setTitle("+Προτιμήσεις", for: .normal)
                questionnaireButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 14)
                questionnaireButton.setTitleColor(UIColor(red: 0.31, green: 0.62, blue: 0.18, alpha: 1.00), for: .normal)
                questionnaireButton.backgroundColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00)
                questionnaireButton.frame = CGRect(x: 0.0, y: 0.0, width: questionnaireButton.intrinsicContentSize.width, height: questionnaireButton.intrinsicContentSize.height)
            }
            questionnaireButton.layer.cornerRadius = 7.0
        }
    }

    public override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if let headerView = tableView.tableHeaderView {

            let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            var headerFrame = headerView.frame

            //Comparison necessary to avoid infinite loop
            if height != headerFrame.size.height {
                headerFrame.size.height = height
                headerView.frame = headerFrame
                tableView.tableHeaderView = headerView
            }
        }
    }
    
    // MARK: - Actions
    @IBAction func qustionnaireButtonAction(_ sender: Any) {
        swiftApi().openQuestionnaire(self);
    }
    
    @IBAction func dfyEarnButtonAction(_ sender: Any) {
       // analysis_pressed event
       let dealsAnalysis = swiftApi.WarplyDealsAnalysisEventModel()
       dealsAnalysis._isPressed = true
       SwiftEventBus.post("analysis_pressed", sender: dealsAnalysis)
    }
    @IBAction func couponEarnButtonAction(_ sender: Any) {

        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)
    }
    
}

// MARK: - TableView
extension WalletViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.coupons.count
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120.0 + 30.0
//        return UITableViewAutomaticDimension
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CouponsTableViewCellId", for: indexPath) as! CouponsTableViewCell
        
        cell.configureCell(coupon: coupons[indexPath.row])
        
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
       let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
       let vc = storyboard.instantiateViewController(withIdentifier: "CouponBarcodeViewController") as! SwiftWarplyFramework.CouponBarcodeViewController
       vc.coupon = coupons[indexPath.row]
       self.navigationController?.pushViewController(vc, animated: true)
        
    }
}