GiftsViewController.swift 19.5 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
//
//  GiftsViewController.swift
//  WarplySDKFrameworkIOS
//
//  Created by Βασιλης Σκουρας on 5/5/22.
//

import Foundation
import UIKit
// import SwiftEventBus

@objc public class GiftsViewController: UIViewController {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var topBorderShadow: UIImageView!
    
    public var campaigns:Array<swiftApi.CampaignItemModel> = [] {
        didSet {
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
    public var seasonalList:Array<swiftApi.LoyaltyGiftsForYouPackage> = swiftApi().getSeasonalList()
    public var ccmsList:Array<swiftApi.LoyaltyContextualOfferModel> = swiftApi().getCCMSLoyaltyCampaigns()
    public var loyaltyList:Array<swiftApi.CampaignItemModel> = swiftApi().mergeGFYCCMSLoyaltyCampaigns(campaigns: swiftApi().getCCMSLoyaltyCampaigns())
    
    var timerGFY: DispatchSourceTimer?
    var seconds: Int = 0
    
    public override func viewDidLoad() {
        super.viewDidLoad()

        self.hidesBottomBarWhenPushed = true

        setBackButton()
        setNavigationTitle("GIFTS FOR YOU", "bold")
        
        tableView.delegate = self
        tableView.dataSource = self

        // SwiftEventBus.onMainThread(self, name: "ccms_retrieved") { result in
        //     print("===== SwiftEventBus ccms_retrieved =====")
            
        //     self.refreshData()
            
        // }

        // SwiftEventBus.onMainThread(self, name: "campaigns_retrieved") { result in
        //     print("===== SwiftEventBus campaigns_retrieved =====")
            
        //     self.refreshData()
            
        // }

        // SwiftEventBus.onMainThread(self, name: "seasonals_retrieved") { result in
        //     print("===== SwiftEventBus seasonals_retrieved =====")
            
        //     self.refreshData()

        // }
        
//        tableView.clipsToBounds = true
//        tableView.layer.cornerRadius = 30
//        tableView.layer.maskedCorners = [ .layerMinXMinYCorner] // Top left corner radius
        tableView.contentInset.top = 25
        
        // Add Top left corner radius
//        mainView.clipsToBounds = true
//        mainView.layer.cornerRadius = 30
//        mainView.layer.maskedCorners = [ .layerMinXMinYCorner] // Top left corner radius
        mainView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.00)
        
//        let image = UIImage(named: "top_border_shadow", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)!
//       var aspectR: CGFloat = 0.0
//
//       aspectR = image.size.width/image.size.height
//
//       topBorderShadow.translatesAutoresizingMaskIntoConstraints = false
//       topBorderShadow.image = image
//       topBorderShadow.contentMode = .scaleAspectFill
//
//        NSLayoutConstraint.activate([
//            topBorderShadow.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 0),
//            topBorderShadow.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 0),
//            topBorderShadow.trailingAnchor.constraint(equalTo: mainView.trailingAnchor, constant: 0),
//            topBorderShadow.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width),
//            topBorderShadow.heightAnchor.constraint(equalTo: topBorderShadow.widthAnchor, multiplier: 1/aspectR)
//        ])
        
    }

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

        self.startTimer()

        self.navigationController?.hideHairline()
    }

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

        self.stopTimer()
    }
    
    // MARK: - Functions
    func refreshData() -> Void {
        var tempCampaigns:Array<swiftApi.CampaignItemModel> = []
        self.campaigns = []
        self.seasonalList = swiftApi().getSeasonalList()
        self.ccmsList = swiftApi().getCCMSLoyaltyCampaigns()
        self.loyaltyList = swiftApi().mergeGFYCCMSLoyaltyCampaigns(campaigns: swiftApi().getCCMSLoyaltyCampaigns())

        if (self.seasonalList.count > 0) {
            for seasonalItem in self.seasonalList {
                let newCampaign = swiftApi.CampaignItemModel()
                newCampaign._title = seasonalItem._title
                newCampaign._logo_url = seasonalItem._imageUrl
                newCampaign._loyaltyPackageId = seasonalItem._loyaltyPackageId
                tempCampaigns.append(newCampaign)
            }
        }
        
        if (self.ccmsList.count > 0) {
            for ccmsItem in self.ccmsList {
                if (((ccmsItem._loyaltyCampaignId == "") || (ccmsItem._loyaltyCampaignId == "NA")) && (ccmsItem._zone == "COSMOTE_APP_GIFTS4U")) {
                    let newCampaign = swiftApi.CampaignItemModel()
                    newCampaign._title = ccmsItem._title
                    newCampaign._logo_url = ccmsItem._imageUrl
                    newCampaign._ccms = ccmsItem
                    tempCampaigns.append(newCampaign)
                }
            }
        }

        if (self.loyaltyList.count > 0) {
            tempCampaigns = tempCampaigns + self.loyaltyList
        }
        
        self.campaigns = tempCampaigns
        self.tableView.reloadData()
    }

    func startTimer() {
        print("========= GFY Timer Started! =========")

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

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

            }
        }
        timerGFY!.resume()
    }

    func stopTimer() {
        print("========= GFY Timer Stopped! =========")
        timerGFY?.cancel()
        timerGFY = nil

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

        seconds = 0
    }

}

// MARK: - TableView
extension GiftsViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.campaigns.count
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140.0 + 10.0
//        return UITableViewAutomaticDimension
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "InboxTableViewCellId", for: indexPath) as! InboxTableViewCell

        let isCcmsOffer = (campaigns[indexPath.row].ccms_offer != nil) && (campaigns[indexPath.row].ccms_offer != "") && (campaigns[indexPath.row].ccms_offer == "true")
        
        if (campaigns[indexPath.row]._type != nil && campaigns[indexPath.row]._type == "telco") {
            let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
            let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaigns[indexPath.row].session_uuid }

            if (loyaltyCampaignIdExists == true) {
                for item in ccmsCampaigns {
                    if (item._loyaltyCampaignId == campaigns[indexPath.row].session_uuid) {
                        cell.configureCell(ccms: item)
                        break;
                    }
                }
            }
            
        } else if (campaigns[indexPath.row].session_uuid != nil && campaigns[indexPath.row].session_uuid != "" && isCcmsOffer) {

            let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
            let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaigns[indexPath.row].session_uuid }

            if (loyaltyCampaignIdExists == true) {
                for item in ccmsCampaigns {
                    if (item._loyaltyCampaignId == campaigns[indexPath.row].session_uuid) {
                        cell.configureCell(ccms: item)
                        break;
                    }
                }
            }

        } else {
            cell.configureCell(campaign: campaigns[indexPath.row])
        }
        
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (campaigns[indexPath.row]._ccms != nil) {

            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
            firebaseEvent._eventName = "loyalty_sdk_offer_selected"
            firebaseEvent.setParameter = ("name", (campaigns[indexPath.row]._ccms?._title ?? ""))
            firebaseEvent.setParameter = ("type", "gift")
            // SwiftEventBus.post("firebase", sender: firebaseEvent)
            
            swiftApi().logTrackersEvent("click", ("Contextual:" + (campaigns[indexPath.row]._ccms?._sessionId ?? "")))

            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            let vc = storyboard.instantiateViewController(withIdentifier: "ContextualViewController") as! SwiftWarplyFramework.ContextualViewController
            vc.ccms = campaigns[indexPath.row]._ccms
            self.navigationController?.pushViewController(vc, animated: true)

            if let sessionUuid = campaigns[indexPath.row].session_uuid {
                getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
            }
            
        } else if (campaigns[indexPath.row]._type != nil && campaigns[indexPath.row]._type == "telco") {
            let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
            let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaigns[indexPath.row].session_uuid }

            if (loyaltyCampaignIdExists == true) {
                for item in ccmsCampaigns {
                    if (item._loyaltyCampaignId == campaigns[indexPath.row].session_uuid) {
                        
                        swiftApi().logTrackersEvent("click", ("Telco:" + (item._sessionId)))

                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_sdk_offer_selected"
                        firebaseEvent.setParameter = ("name", (item._title))
                        firebaseEvent.setParameter = ("type", "gift")
                        // SwiftEventBus.post("firebase", sender: firebaseEvent)

                        let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
                        let vc = storyboard.instantiateViewController(withIdentifier: "TelcoViewController") as! SwiftWarplyFramework.TelcoViewController
                        vc.ccms = item
                        vc.campaign = campaigns[indexPath.row]
                        self.navigationController?.pushViewController(vc, animated: true)

                        if let sessionUuid = campaigns[indexPath.row].session_uuid {
                            getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
                        }
                        break;
                    }
                }
            }
            
        } else if (campaigns[indexPath.row]._campaign_type == "coupon") {
            let couponsetUuid = campaigns[indexPath.row]._couponset
            
            if (couponsetUuid != "") {
                let couponsetsList = swiftApi().getCouponSetList()
                
                for item in couponsetsList {
                    if (item.uuid == couponsetUuid) {
                        
                        swiftApi().logTrackersEvent("click", ("Loyalty:" + (campaigns[indexPath.row].session_uuid ?? "")))

                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_sdk_offer_selected"
                        firebaseEvent.setParameter = ("name", (item.name ?? ""))
                        firebaseEvent.setParameter = ("type", "coupon")
                        // SwiftEventBus.post("firebase", sender: firebaseEvent)

                       let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
                       let vc = storyboard.instantiateViewController(withIdentifier: "CouponViewController") as! SwiftWarplyFramework.CouponViewController
                       vc.couponset = item
                       vc.campaign = campaigns[indexPath.row]

                        let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
                        let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaigns[indexPath.row].session_uuid }

                        if (loyaltyCampaignIdExists == true) {
                            for item in ccmsCampaigns {
                                if (item._loyaltyCampaignId == campaigns[indexPath.row].session_uuid) {
                                    vc.ccms = item
                                    break;
                                }
                            }
                        }

                        self.navigationController?.pushViewController(vc, animated: true)

                        if let sessionUuid = campaigns[indexPath.row].session_uuid {
                            getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
                        }

                        break;
                    }
                }
            }
                
        } else {
            if (campaigns[indexPath.row].session_uuid != nil && campaigns[indexPath.row].session_uuid != "") {

                let status = swiftApi().getNetworkStatus()
                if (status == -1 || status == 0) {
                    self.showDialog("Δεν υπάρχει σύνδεση","Αυτή τη στιγμή βρίσκεσαι εκτός σύνδεσης. Παρακαλούμε βεβαιώσου ότι είσαι συνδεδεμένος στο διαδίκτυο και προσπάθησε ξανά.")
                } else {

                    let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
                    let vc = storyboard.instantiateViewController(withIdentifier: "CampaignViewController") as! SwiftWarplyFramework.CampaignViewController
                    var url = ""
                    var params = ""
                    let isCcmsOffer = (campaigns[indexPath.row].ccms_offer != nil) && (campaigns[indexPath.row].ccms_offer != "") && (campaigns[indexPath.row].ccms_offer == "true")
                    
                    if (isCcmsOffer) {
                        let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()

                        let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaigns[indexPath.row].session_uuid }

                        if (loyaltyCampaignIdExists == true) {
                            var ccmsCampaignFound:swiftApi.LoyaltyContextualOfferModel = swiftApi.LoyaltyContextualOfferModel()
                            for item in ccmsCampaigns {
                                if (item._loyaltyCampaignId == campaigns[indexPath.row].session_uuid) {
                                    ccmsCampaignFound = item
                                }
                            }
                            swiftApi().logTrackersEvent("click", ("Contextual:" + (ccmsCampaignFound._sessionId)))
                            
                            url = swiftApi().constructCcmsUrl(campaigns[indexPath.row], ccmsCampaignFound)
                            params = swiftApi().constructCcmsParams(campaigns[indexPath.row], ccmsCampaignFound)

                        } else {
                            url = swiftApi().constructCampaignUrl(campaigns[indexPath.row])
                            params = swiftApi().constructCampaignParams(campaigns[indexPath.row])

                        }

                        let encoder = JSONEncoder()
                        encoder.outputFormatting = .prettyPrinted
                        let data = try! encoder.encode(campaigns[indexPath.row])

                        print("CCMS_CLICK " + String(data: data, encoding: .utf8)!)

                    } else {
                        swiftApi().logTrackersEvent("click", ("Loyalty:" + (campaigns[indexPath.row].session_uuid ?? "")))
                        
                        url = swiftApi().constructCampaignUrl(campaigns[indexPath.row])
                        params = swiftApi().constructCampaignParams(campaigns[indexPath.row])

                        let encoder = JSONEncoder()
                        encoder.outputFormatting = .prettyPrinted
                        let data = try! encoder.encode(campaigns[indexPath.row])

                        print("GFY_CLICK " + String(data: data, encoding: .utf8)!)
                    }
                    print("CampaignUrl url onclick: " + url)
                    vc.campaignUrl = url
                    vc.params = params
                    self.navigationController?.pushViewController(vc, animated: true)

                    if let sessionUuid = campaigns[indexPath.row].session_uuid {
                        getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
                    }
                }

            } else {
                let seasonalEvent = swiftApi.LoyaltyGiftsForYouOfferClickEvent()
                seasonalEvent._title = campaigns[indexPath.row]._title ?? ""
                seasonalEvent._imageUrl = campaigns[indexPath.row]._logo_url ?? ""
                seasonalEvent._loyaltyPackageId = campaigns[indexPath.row]._loyaltyPackageId ?? ""
                // SwiftEventBus.post("seasonal", sender: seasonalEvent)

                let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                firebaseEvent._eventName = "loyalty_sdk_offer_selected"
                firebaseEvent.setParameter = ("name", (campaigns[indexPath.row]._title ?? ""))
                firebaseEvent.setParameter = ("type", "seasonal")
                // SwiftEventBus.post("firebase", sender: firebaseEvent)
            }
        }
    }


    func getSingleCampaignAsyncRequest(sessionUuid: String) {
        swiftApi().getSingleCampaignAsync(sessionUuid: sessionUuid, getSingleCampaignCallback)
    }

    func getSingleCampaignCallback (_ getSingleCampaignData: swiftApi.VerifyTicketResponseModel?) -> Void {
        if (getSingleCampaignData != nil) {
            DispatchQueue.main.async {
            }
        } else {
        }
    }


    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:
                print("default")

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

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