WalletViewController.swift 27 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
//
//  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!
    @IBOutlet weak var activeCodeScrollView: UIScrollView!
    @IBOutlet weak var activeCodeScrollViewHeight: NSLayoutConstraint!
    @IBOutlet weak var activeCodeContentView: UIView!
    @IBOutlet weak var activeCodeContentViewHeight: NSLayoutConstraint!
    
    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()

    var timerWallet: DispatchSourceTimer?
    var seconds: Int = 0
   
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true

        setBackButton()
        setNavigationTitle("My Rewards")
        
        tableView.delegate = self
        tableView.dataSource = self

        print("Active Gifts Count: " + String(coupons.count))

        // if ((profile != nil) && (profile?._nonTelco == true)) {
        if (swiftApi().getUserNonTelco() == true) {
            showDialog("Αδυναμία ενεργοποίησης", "Πρόσθεσε σύνδεση COSMOTE σταθερής, κινητής ή TV για να έχεις πρόσβαση στις προσφορές.");
        }
        
       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_2", 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: 26)
            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
            questionnaireButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 10, bottom: 3, right: 10)
        } 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: 26)
            questionnaireButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        }
        
        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) ?? UIFont.systemFont(ofSize: 16)]
        let attrBold = [NSAttributedString.Key.font : UIFont(name: "PFSquareSansPro-Bold", size: 17) ?? UIFont.boldSystemFont(ofSize: 16)]
        
        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"
                // dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                
                // 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) + 1) : ""
                }
                
                activeCodesCountLabel.text = "Ενεργός κωδικός:"
                // activeCodeLabel.text = dfyCoupons[0]._code
                let newLabel = CopyableLabel()
                newLabel.text = String(dfyCoupons[0]._code)
                newLabel.font = UIFont(name: "PFSquareSansPro-Bold", size: 19)
                newLabel.textColor = UIColor(rgb: 0x3C5365)
                newLabel.frame.size.width = newLabel.intrinsicContentSize.width
                newLabel.frame.size.height = newLabel.intrinsicContentSize.height // tagHeight
                activeCodeContentView.addSubview(newLabel)
                // set the btn frame origin
                newLabel.frame.origin.x = 0
                newLabel.frame.origin.y = 0
                let scrollHeight = newLabel.intrinsicContentSize.height
                activeCodeContentViewHeight.constant = scrollHeight
                activeCodeScrollViewHeight.constant = scrollHeight

                activeCodeExpirationLabel.isHidden = false
                if (daysFromNow == "1") {
                    activeCodeExpirationLabel.text = "Λήγει σε " + daysFromNow + " ημέρα"
                } else {
                    activeCodeExpirationLabel.text = "Λήγει σε " + daysFromNow + " ημέρες"
                }
                
            } else {
                var tagHeight:CGFloat = 30
                let tagPadding: CGFloat = 0
                let tagSpacingX: CGFloat = 0
                let tagSpacingY: CGFloat = 2
                
                let containerWidth = activeCodeContentView.frame.size.width
                
                var currentOriginX: CGFloat = 0
                var currentOriginY: CGFloat = 0

                // var couponCodesString = ""
                for (index, item) in dfyCoupons.enumerated() {
                    let newLabel = CopyableLabel()
                    newLabel.font = UIFont(name: "PFSquareSansPro-Bold", size: 19)
                    newLabel.textColor = UIColor(rgb: 0x3C5365)

                    if (index == (dfyCoupons.endIndex - 1)) {
                        // couponCodesString += String(item._code)
                        newLabel.text = String(item._code)
                    } else {
                        // couponCodesString += String(item._code) + ", "
                        newLabel.text = String(item._code) + ", "
                    }
                    
                    newLabel.frame.size.width = newLabel.intrinsicContentSize.width + tagPadding
                    newLabel.frame.size.height = newLabel.intrinsicContentSize.height // tagHeight
                    tagHeight = newLabel.intrinsicContentSize.height
                    activeCodeContentView.addSubview(newLabel)
                    
                    // if current X + label width will be greater than container view width
                    //  "move to next row"
                    if currentOriginX + newLabel.frame.width > containerWidth {
                        currentOriginX = 0
                        currentOriginY += tagHeight + tagSpacingY
                    }
                    
                    // set the btn frame origin
                    newLabel.frame.origin.x = currentOriginX
                    newLabel.frame.origin.y = currentOriginY
                    
                    // increment current X by btn width + spacing
                    currentOriginX += newLabel.frame.width + tagSpacingX
                }
                
                activeCodesCountLabel.text = String(dfyCoupons.count) + " Ενεργοί κωδικοί:"
                // activeCodeLabel.text = couponCodesString
                activeCodeExpirationLabel.isHidden = true

                // update container view height
                activeCodeContentViewHeight.constant = currentOriginY + tagHeight
                if ((currentOriginY + tagHeight) <= (2 * tagHeight + tagSpacingY)) {
                    activeCodeScrollViewHeight.constant = currentOriginY + tagHeight
                } else {
                    activeCodeScrollViewHeight.constant = 2 * tagHeight + tagSpacingY
                }
            }
        } else {
            activeCodeLabel.text = "-"
            activeCodeExpirationLabel.text = ""

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

        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
        }

    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "LoyaltyWalletScreen")

        addNavShadow()
        
        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: 26)
                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
                questionnaireButton.contentEdgeInsets = UIEdgeInsets(top: 7, left: 10, bottom: 3, right: 10)
            } 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: 26)
            questionnaireButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
            }
            questionnaireButton.layer.cornerRadius = 7.0
        }

        self.coupons = swiftApi().getCouponList()
        self.tableView.reloadData()

        self.startTimer()
    }

    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        self.stopTimer()
        self.navigationController?.navigationBar.layer.shadowOpacity = 0.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: - Functions
    func showDialog(_ alertTitle: String, _ alertSubTitle: String) -> Void {

        let alert = UIAlertController(title: alertTitle, message: alertSubTitle, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
            switch action.style{
                case .default:
                    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 startTimer() {
        print("========= MyRewards Timer Started! =========")

        let queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".wallet.timer")
        timerWallet = DispatchSource.makeTimerSource(queue: queue)
        timerWallet!.schedule(deadline: .now(), repeating: .seconds(1))
        timerWallet!.setEventHandler { [weak self] in
            // do whatever stuff you want on the background queue here here
            print("========= MyRewards interval! =========")

            DispatchQueue.main.async {
                // update your model objects and/or UI here
                self?.seconds = (self?.seconds ?? 0) + 1

            }
        }
        timerWallet!.resume()
    }

    func stopTimer() {
        print("========= MyRewards Timer Stopped! =========")
        timerWallet?.cancel()
        timerWallet = nil

        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
        firebaseEvent._eventName = "time_spent_on_loyalty_sdk"
        firebaseEvent.setParameter = ("name", "MyRewards")
        firebaseEvent.setParameter = ("seconds", String(seconds))
        SwiftEventBus.post("firebase", sender: firebaseEvent)

        seconds = 0
    }
    
    // MARK: - Actions
    @IBAction func qustionnaireButtonAction(_ sender: Any) {
        swiftApi().logTrackersEvent("click", ("LoyaltyWalletScreen:" + "Questionnaire"))
        
        swiftApi().openQuestionnaire(self);
    }
    
    @IBAction func dfyEarnButtonAction(_ sender: Any) {
        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 Wallet")
        SwiftEventBus.post("firebase", sender: firebaseEvent)
        
        swiftApi().logTrackersEvent("click", ("LoyaltyWalletScreen:" + "DealsBanner"))
    }
    @IBAction func couponEarnButtonAction(_ sender: Any) {

        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
        firebaseEvent._eventName = "did_tap_deals_for_you_badge"
        firebaseEvent.setParameter = ("screen", "Loyalty Wallet")
        SwiftEventBus.post("firebase", sender: firebaseEvent)
        
        swiftApi().logTrackersEvent("click", ("LoyaltyWalletScreen:" + "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 activeCodeButtonAction(_ sender: Any) {
        print("Active DFY coupon banner Tapped!")
        
        swiftApi().logTrackersEvent("click", ("LoyaltyWalletScreen:" + "ActiveDealsBanner"))
        
        let couponDetails = swiftApi.ActiveDFYCouponEventModel()
        couponDetails._isPressed = true
        SwiftEventBus.post("dfy_coupon_details", sender: couponDetails)
    }
    
}

// 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 + 8.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 couponSetData: swiftApi.CouponSetItemModel? = coupons[indexPath.row].couponset_data
        let couponName = couponSetData?.name ?? ""
        swiftApi().logTrackersEvent("click", ("Coupon:" + couponName))
        
       let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
       let vc = storyboard.instantiateViewController(withIdentifier: "CouponBarcodeViewController") as! SwiftWarplyFramework.CouponBarcodeViewController
       vc.coupon = coupons[indexPath.row]
       vc.isFromWallet = true
       self.navigationController?.pushViewController(vc, animated: true)
        
    }
}