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

import Foundation
import UIKit
import SwiftEventBus

@objc public class MFYViewController: UIViewController {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var tableView: UITableView!

    var categories: Array<CampaignCategory> = [CampaignCategory]()
    
    public var campaigns:Array<swiftApi.CampaignItemModel> = []
    public var loyaltyList:Array<swiftApi.CampaignItemModel> = swiftApi().mergeMFYCCMSLoyaltyCampaigns(campaigns: swiftApi().getCCMSLoyaltyCampaigns())
    public var ccmsList:Array<swiftApi.LoyaltyContextualOfferModel> = swiftApi().getCCMSLoyaltyCampaigns()

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

        setBackButton()
        setNavigationTitle("MORE 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()
        }
        
        tableView.clipsToBounds = true
        tableView.layer.cornerRadius = 30
        tableView.layer.maskedCorners = [ .layerMinXMinYCorner] // Top left corner radius
        tableView.contentInset.top = 50
        
        // 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.22, green: 0.32, blue: 0.40, alpha: 1.00)
        
    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.refreshData()

        self.startTimer()
    }

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

        self.stopTimer()
    }

    // MARK: - Functions
    func refreshData() -> Void {
        self.loyaltyList = swiftApi().mergeMFYCCMSLoyaltyCampaigns(campaigns: swiftApi().getCCMSLoyaltyCampaigns())
        self.ccmsList = swiftApi().getCCMSLoyaltyCampaigns()
        // var tempCampaigns:Array<swiftApi.CampaignItemModel> = loyaltyList

        var newData = [CampaignCategory]()
        
        // parse campaigns
        var campaignsDict = [String:CampaignCategory]()
        for item in loyaltyList {
            guard let title = item._category_title else {
                continue
            }
            
            if (title.isEmpty) {
                continue
            }
            
            var category = campaignsDict[title]
            if (category == nil) {
                category = CampaignCategory(title)
                campaignsDict[title] = category
                newData.append(category!)
            }
            
            category?.items.append(item)
        }
        newData = newData.sorted(by: { $0.index < $1.index })

        // parse ccms
        if (self.ccmsList.count > 0) {
            let category = CampaignCategory("ΑΛΛΕΣ")
            for ccmsItem in self.ccmsList {
                if (((ccmsItem._loyaltyCampaignId == "") || (ccmsItem._loyaltyCampaignId == "NA")) && (ccmsItem._zone == "COSMOTE_APP_MORE4U")) {
                     let newCampaign = swiftApi.CampaignItemModel()
                     newCampaign._title = ccmsItem._title
                     newCampaign._logo_url = ccmsItem._imageUrl
                    newCampaign._subtitle = ccmsItem._subtitle
                    newCampaign._message = ccmsItem._message
                     newCampaign._ccms = ccmsItem
                    //  tempCampaigns.append(newCampaign)
                    category.items.append(newCampaign)
                }
            }
            newData.append(category)
        }

        // self.campaigns = tempCampaigns
        self.categories = newData
        self.tableView.reloadData()
    }

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

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

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

            }
        }
        timerMFY!.resume()
    }

    func stopTimer() {
        print("========= MFY Timer Stopped! =========")
        timerMFY?.cancel()
        timerMFY = nil

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

        seconds = 0
    }
    
}

// MARK: - TableView
extension MFYViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        // return 1
        return self.categories.count
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // return self.campaigns.count
        return self.categories[section].items.count
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 220.0 + 10.0
//        return UITableViewAutomaticDimension
    }

    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 43))
         view.backgroundColor =  .clear
        
        let titleLabel = UILabel(frame: CGRect(x: 20, y: 5, width: view.frame.width - 20, height: 43))
        titleLabel.font = UIFont(name: "PFSquareSansPro-Bold", size: 21)
        titleLabel.textColor = UIColor(rgb: 0xF4F4F4)
        titleLabel.text = categories[section].name
        
        view.addSubview(titleLabel)
        return view
    }

    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 43
    }
    
    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MFYInboxTableViewCellId", for: indexPath) as! MFYInboxTableViewCell

        let campaign = categories[indexPath.section].items[indexPath.row]
        
        if (campaign._type != nil && campaign._type == "telco") {
            let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
            let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaign.session_uuid }

            if (loyaltyCampaignIdExists == true) {
                for item in ccmsCampaigns {
                    if (item._loyaltyCampaignId == campaign.session_uuid) {
                        cell.configureCell(ccms: item)
                        break;
                    }
                }
            }
            
        } else {
            cell.configureCell(campaign: campaign)
        }
        
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let campaign = categories[indexPath.section].items[indexPath.row]
        
        if (campaign._ccms != nil) {

            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
            firebaseEvent._eventName = "loyalty_sdk_offer_selected"
            firebaseEvent.setParameter = ("name", (campaign._ccms?._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: "ContextualViewController") as! SwiftWarplyFramework.ContextualViewController
            vc.ccms = campaign._ccms
            self.navigationController?.pushViewController(vc, animated: true)

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

            if (loyaltyCampaignIdExists == true) {
                for item in ccmsCampaigns {
                    if (item._loyaltyCampaignId == campaign.session_uuid) {

                        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 = campaign
                        self.navigationController?.pushViewController(vc, animated: true)

                        if let sessionUuid = campaign.session_uuid {
                            getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
                        }
                    }
                }
            }
            
        } else if (campaign._campaign_type == "coupon") {
            let couponsetUuid = campaign._couponset
            
            if (couponsetUuid != "") {
                let couponsetsList = swiftApi().getCouponSetList()
                
                for item in couponsetsList {
                    if (item.uuid == couponsetUuid) {

                        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 = campaign

                        let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()
                        let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaign.session_uuid }

                        if (loyaltyCampaignIdExists == true) {
                            for item in ccmsCampaigns {
                                if (item._loyaltyCampaignId == campaign.session_uuid) {
                                    vc.ccms = item
                                    break;
                                }
                            }
                        }
                        
                       self.navigationController?.pushViewController(vc, animated: true)

                        if let sessionUuid = campaign.session_uuid {
                            getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
                        }

                        break;
                    }
                }
            }
                
        } else {
            // let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            // let vc = storyboard.instantiateViewController(withIdentifier: "CampaignViewController") as! SwiftWarplyFramework.CampaignViewController
            // let url = swiftApi().constructCampaignUrl(campaign)
            //     print("CampaignUrl url onclick: " + url)
            // vc.campaignUrl = url
            // self.navigationController?.pushViewController(vc, animated: true)

            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 = (campaign.ccms_offer != nil) && (campaign.ccms_offer != "") && (campaign.ccms_offer == "true")
            
            if (isCcmsOffer) {
                let ccmsCampaigns = swiftApi().getCCMSLoyaltyCampaigns()

                let loyaltyCampaignIdExists = ccmsCampaigns.contains { $0._loyaltyCampaignId == campaign.session_uuid }

                if (loyaltyCampaignIdExists == true) {
                    var ccmsCampaignFound:swiftApi.LoyaltyContextualOfferModel = swiftApi.LoyaltyContextualOfferModel()
                    for item in ccmsCampaigns {
                        if (item._loyaltyCampaignId == campaign.session_uuid) {
                            ccmsCampaignFound = item
                        }
                    }
                    url = swiftApi().constructCcmsUrl(campaign, ccmsCampaignFound)
                    params = swiftApi().constructCcmsParams(campaign, ccmsCampaignFound)

                } else {
                    url = swiftApi().constructCampaignUrl(campaign)
                    params = swiftApi().constructCampaignParams(campaign)

                }

                let encoder = JSONEncoder()
                encoder.outputFormatting = .prettyPrinted
                let data = try! encoder.encode(campaign)

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

            } else {
                url = swiftApi().constructCampaignUrl(campaign)
                params = swiftApi().constructCampaignParams(campaign)

                let encoder = JSONEncoder()
                encoder.outputFormatting = .prettyPrinted
                let data = try! encoder.encode(campaign)

                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 = campaign.session_uuid {
                getSingleCampaignAsyncRequest(sessionUuid: sessionUuid)
            }
        }
    }


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

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