CampaignViewController.swift 16.5 KB
//
//  CampaignViewController.swift
//  SwiftWarplyFramework
//
//  Created by Βασιλης Σκουρας on 11/5/22.
//

import Foundation
import UIKit
import WebKit
import SwiftEventBus

var timer2: DispatchSourceTimer?

@objc public class CampaignViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
    @IBOutlet weak var webview: WKWebView!
    
    public var campaignUrl: String = ""
    public var params: String = ""
    public var showHeader: Bool = false

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if (!showHeader) {
            // navigationController?.setNavigationBarHidden(true, animated: animated)
            self.navigationController?.isNavigationBarHidden = true
        }
    }

    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if (!showHeader) {
            // navigationController?.setNavigationBarHidden(false, animated: animated)
            self.navigationController?.isNavigationBarHidden = false
        }

        stopTimer()

        let persistedSteps = swiftApi().getSteps()
        if (persistedSteps > 0) {

            let currentDateTime = Date()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateString = dateFormatter.string(from: currentDateTime)

            swiftApi().setPacingDetailsAsync(persistedSteps, dateString, setPacingDetailsAsyncCallback)
        }
        
        func setPacingDetailsAsyncCallback (_ responseData: swiftApi.GenericResponseModel?) -> Void {
            if (responseData != nil) {
                DispatchQueue.main.async {
                    if (responseData?.getStatus == 1) {
                        // print("===== steps sent on back button press ====")
                    }
                }
            } else {
            }
        }
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()

        var campaignUrl = campaignUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("Webview url: " + (campaignUrl ?? ""))
        
        self.hidesBottomBarWhenPushed = true

        if (showHeader) {
            setBackButton()
        }
        
        webview.navigationDelegate = self
        if let url = URL(string: campaignUrl ?? "") {
            webview.load(URLRequest(url: url))
            webview.allowsBackForwardNavigationGestures = true
        }

        webview.configuration.userContentController.add(self, name: "Cosmote")
    }

    // MARK: - Functions
    func startTimer() {
        // print("========= Webview Timer Started! =========")

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

            DispatchQueue.main.async {
                // update your model objects and/or UI here
                let metersParam = swiftApi().getMetersWebview()
                let scriptSource = "passMeters(\(metersParam));"
                
                self?.webview.evaluateJavaScript(scriptSource, completionHandler: { (object, error) in
                    // print("==== object ====")
                    // print(object)
                    // print("==== error ====")
                    // print(error)

                    swiftApi().setSavedStepsWebview(swiftApi().getSavedStepsWebview() + swiftApi().getStepsWebview())
                    swiftApi().setStepsWebview(0)
                    swiftApi().setMetersWebview(0.0)

                    // print("==== SavedStepsWebview ====")
                    // print(swiftApi().getSavedStepsWebview())
                })
            }
        }
        timer2!.resume()
    }

    func stopTimer() {
        // print("========= Webview Timer Stopped! =========")
        timer2?.cancel()
        timer2 = nil
    }

    // MARK: - API Calls
    func startTrackingSteps() {
        swiftApi().startTrackingSteps(startTrackingStepsCallback)
    }
    
    func startTrackingStepsCallback (_ steps: Int) -> Void {
        DispatchQueue.main.async {
        }
    }

    // MARK: - WKNavigationDelegate
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        let scriptSource = "passParams(\(params));"
        
        webView.evaluateJavaScript(scriptSource, completionHandler: { (object, error) in
            // print("==== object ====")
            // print(object)
            // print("==== error ====")
            // print(error)

            DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                self.startTimer()
            }
        })
    }
    
    // MARK: - WKScriptMessageHandler
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if let event = message.body as? String {
            let eventArray = event.split(separator: ":")
            
            if (eventArray[0] == "event") {
                if (eventArray[1] == "closeArtwork") {

                    self.navigationController?.popViewController(animated: true)
                    
                } else if (eventArray[1] == "addUserTag") {
                    // SwiftEventBus.post("questionnaire", sender: questionnaireEvent)

                    swiftApi().getProfileAsync(getProfileCallback)

                    func getProfileCallback (_ profileData: swiftApi.ProfileModel?) -> Void {
                        if (profileData != nil) {
                            DispatchQueue.main.async {
                                swiftApi().getCampaignsAsyncNew(language: "en", filters: [String : Any](), getCampaignsCallback)

                                func getCampaignsCallback (_ campaignsData: Array<swiftApi.CampaignItemModel>?) -> Void {
                                    if (campaignsData != nil) {
                                        DispatchQueue.main.async {
                                            let questionnaireEvent = swiftApi.QuestionnaireEventModel()
                                            questionnaireEvent._name = String(eventArray[1])
                                            if (eventArray.count > 2) {
                                                questionnaireEvent._parameter = String(eventArray[2])
                                                swiftApi().setUserTag(String(eventArray[2]))
                                            } else {
                                                questionnaireEvent._parameter = ""
                                                swiftApi().setUserTag("")
                                            }
                                            SwiftEventBus.post("questionnaire", sender: questionnaireEvent)
                                            SwiftEventBus.post("campaigns_retrieved")
                                        }
                                    } else {
                                    }
                                }
                                
                            }
                        } else {
                        }
                    }

                    
                } else if (eventArray[1] == "couponRetrieved") {
                    let couponEvent = swiftApi.CouponEventModel()
                    SwiftEventBus.post("coupon_retrieved", sender: couponEvent)

                    swiftApi().getCouponsAsync(getCouponsCallback)
                    swiftApi().getCampaignsAsyncNew(language: "en", filters: [String : Any](), getCampaignsCallback)
                    
                    func getCouponsCallback (_ couponsData: Array<swiftApi.CouponItemModel>?) -> Void {
                        if (couponsData != nil) {
                            
                            DispatchQueue.main.async {
                                SwiftEventBus.post("coupons_fetched")
                            }
                        } else {
                        }
                    }

                    func getCampaignsCallback (_ campaignsData: Array<swiftApi.CampaignItemModel>?) -> Void {
                        if (campaignsData != nil) {
                            DispatchQueue.main.async {
                                SwiftEventBus.post("campaigns_retrieved")
                            }
                        } else {
                        }
                    }
                    
                } else if (eventArray[1] == "ccmsRetrieved") {
                   let ccmsEnabled = swiftApi.WarplyCCMSEnabledModel()
                    ccmsEnabled._isActivated = true
                    SwiftEventBus.post("ccms_enabled", sender: ccmsEnabled)

                } else if (eventArray[1] == "couponShared") {
                    
                }
                else if (eventArray[1] == "steps" && eventArray[2] == "widgetDisabled") {
                    let pacingWidget = swiftApi.WarplyPacingCardEventModel()
                    pacingWidget._isVisible = false
                   SwiftEventBus.post("pacing_widget", sender: pacingWidget)
                    
                } else if (eventArray[1] == "steps" && eventArray[2] == "widgetEnabled") {
                    let pacingWidget = swiftApi.WarplyPacingCardEventModel()
                    pacingWidget._isVisible = true
                   SwiftEventBus.post("pacing_widget", sender: pacingWidget)
                    
                } 
                else if (eventArray[1] == "steps" && eventArray[2] == "shortcutEnabled") {
                    let pacingEvent = swiftApi.WarplyPacingEventModel()
                    pacingEvent._isVisible = true
                   SwiftEventBus.post("pacing", sender: pacingEvent)

                    if (swiftApi().getTrackingStepsEnabled() == false) {
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_steps_activation"
                        firebaseEvent._parameters = nil
                        SwiftEventBus.post("firebase", sender: firebaseEvent)

                        self.startTrackingSteps()
                    }
                    
                } else if (eventArray[1] == "steps" && eventArray[2] == "shortcutDisabled") {
                    let pacingEvent = swiftApi.WarplyPacingEventModel()
                    pacingEvent._isVisible = false
                   SwiftEventBus.post("pacing", sender: pacingEvent)
                    swiftApi().stopTrackingSteps()
                    
                } else if (eventArray[1] == "request" || eventArray[1] == "response") {
                    print("**************** WARPLY Webview Log START *****************")
                    print(event)
                    print("**************** WARPLY Webview Log END *****************")

                } else if (eventArray[1] == "loyalty_questionnaire_selected") {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_questionnaire_selected"
                    firebaseEvent.setParameter = ("completed", "true")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)
                    
                } else if (eventArray[1] == "loyalty_questionnaire_answer_again") {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_questionnaire_answer_again"
                    firebaseEvent._parameters = nil
                    SwiftEventBus.post("firebase", sender: firebaseEvent)
                    
                } else if (eventArray[1] == "loyalty_questionnaire_answers_deleted") {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_questionnaire_answers_deleted"
                    firebaseEvent._parameters = nil
                    SwiftEventBus.post("firebase", sender: firebaseEvent)
                    
                } else if (eventArray[1] == "loyalty_questionnaire_later") {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_questionnaire_later"
                    firebaseEvent.setParameter = ("completed", "false")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                } else if (eventArray[1] == "loyalty_sdk_offer_selected") {
                    var name: String = ""
                    if (eventArray.count > 2) {
                        name = String(eventArray[2])
                    } else {
                        name = ""
                    }
                    
                    var type: String = ""
                    if (eventArray.count > 3) {
                        type = String(eventArray[3])
                    } else {
                        type = ""
                    }
                    
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_sdk_offer_selected"
                    firebaseEvent.setParameter = ("name", name)
                    firebaseEvent.setParameter = ("type", type)
                    SwiftEventBus.post("firebase", sender: firebaseEvent)
                    
                } else if (eventArray[1] == "loyalty_offer_activated") {
                    var name: String = ""
                    if (eventArray.count > 2) {
                        name = String(eventArray[2])
                    } else {
                        name = ""
                    }
                    
                    var type: String = ""
                    if (eventArray.count > 3) {
                        type = String(eventArray[3])
                    } else {
                        type = ""
                    }
                    
                    var successful: String = ""
                    if (eventArray.count > 4) {
                        successful = String(eventArray[4])
                    } else {
                        successful = ""
                    }
                    
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", name)
                    firebaseEvent.setParameter = ("type", type)
                    firebaseEvent.setParameter = ("successful", successful)
                    SwiftEventBus.post("firebase", sender: firebaseEvent)
                    
                } else if (eventArray[1] == "time_spent_on_loyalty_sdk") {
                    var name: String = ""
                    if (eventArray.count > 2) {
                        name = String(eventArray[2])
                    } else {
                        name = ""
                    }
                    
                    var seconds: String = ""
                    if (eventArray.count > 3) {
                        seconds = String(eventArray[3])
                    } else {
                        seconds = ""
                    }
                    
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "time_spent_on_loyalty_sdk"
                    firebaseEvent.setParameter = ("name", name)
                    firebaseEvent.setParameter = ("seconds", seconds)
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                } else if (eventArray[1] == "refreshToken") {
                    var access_token: String = ""
                    if (eventArray.count > 2) {
                        access_token = String(eventArray[2])
                    } else {
                        access_token = ""
                    }
                    
                    var refresh_token: String = ""
                    if (eventArray.count > 3) {
                        refresh_token = String(eventArray[3])
                    } else {
                        refresh_token = ""
                    }
                    
                    if (access_token != "" && refresh_token != "") {
                        swiftApi().updateRefreshToken(access_token: access_token, refresh_token: refresh_token)
                    }
                }

            }
        }
    }

}