WalletViewController.swift 14.8 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 dfyEarnView: UIView!
    @IBOutlet weak var dfyEarnLabel: UILabel!
    @IBOutlet weak var dfyEarnAmountLabel: UILabel!
    @IBOutlet weak var dfyEarnImage: UIImageView!
    @IBOutlet weak var couponEarnView: UIView!
    @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!

    public var coupons:Array<swiftApi.CouponItemModel> = swiftApi().filterActiveCoupons(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 != 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.systemFont(ofSize: 13, weight: .semibold)
            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.systemFont(ofSize: 13, weight: .semibold)
            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
        
        dfyEarnView.layer.cornerRadius = 5.0
        dfyEarnView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.16).cgColor
        dfyEarnView.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
        dfyEarnView.layer.shadowOpacity = 1.0
        dfyEarnView.layer.shadowRadius = 3.0
        
        var totalCouponValue = swiftApi().getDealsCouponsSum()
        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!"
        dfyEarnAmountLabel.text = totalCouponValueString + "€"
        
        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) + " κουπόνια!"
        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
        }
    }

    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.systemFont(ofSize: 13, weight: .semibold)
                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.systemFont(ofSize: 13, weight: .semibold)
                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) {
        // TODO: couponEarnButtonAction
        print("couponEarnButtonAction Tapped!")
    }
    
}

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