ContextualViewController.swift 9.18 KB
//
//  ContextualViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 2/9/22.
//

import UIKit
import SwiftEventBus

@objc public class ContextualViewController: UIViewController, UIPopoverControllerDelegate {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var backgroundImage: UIImageView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var scrollContentView: UIView!
    @IBOutlet weak var couponImage: UIImageView!
    @IBOutlet weak var couponImageHeight: NSLayoutConstraint!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var redeemButton: UIButton!
    @IBOutlet weak var topBorderLine: UIImageView!
    
    public var ccms: swiftApi.LoyaltyContextualOfferModel?
    
    var selectedNumber: String = ""
    public var numbersList: Array<String> = []
    
    let uiscreen: CGRect = UIScreen.main.bounds

    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true

        // Do any additional setup after loading the view.
        // getProfileRequest()

        numbersList = ccms?._eligibleAssets ?? []
        
        setBackButton()
//        setNavigationTitle("")

       backgroundImage.image = UIImage(named: "coupons_scrollview_white", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        
//        scrollView.clipsToBounds = true
//        scrollView.layer.cornerRadius = 30
//        scrollView.layer.maskedCorners = [ .layerMinXMinYCorner] // Top left corner radius
        
        let image = UIImage(named: "top_border_line", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)!
        var aspectR: CGFloat = 0.0

        aspectR = image.size.width/image.size.height

        topBorderLine.translatesAutoresizingMaskIntoConstraints = false
        topBorderLine.image = image
        topBorderLine.contentMode = .scaleAspectFit

        NSLayoutConstraint.activate([
            topBorderLine.heightAnchor.constraint(equalTo: topBorderLine.widthAnchor, multiplier: 1/aspectR)
        ])
        
        couponImage.load(link: ccms?._imageUrl ?? "", placeholder: UIImage(), cache: URLCache())
        couponImage.contentMode = .scaleAspectFill
        couponImageHeight.constant = self.uiscreen.height * 0.25

        nameLabel.text = ccms?._title ?? ""
        descriptionLabel.text = ccms?._subtitle ?? ""
        
        redeemButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 16)
        redeemButton.setTitle("Ενεργοποίηση", for: .normal)
        redeemButton.setTitleColor(.white, for: .normal)
        redeemButton.backgroundColor = UIColor(red: 0.47, green: 0.75, blue: 0.08, alpha: 1.00)
        redeemButton.layer.cornerRadius = 12.0
        
    }
    
    // MARK: - Functions
    func showConfirmDialog() -> Void {

        let alert = UIAlertController(title: "Ενεργοποίηση υπηρεσίας", message: "Θέλετε να γίνει ενεργοποίηση στο Κινητό μου;", preferredStyle: .alert)

        let cancelButton = UIAlertAction(title: "Άκυρο", style: .default, handler: { action in
            switch action.style{
                case .default:
                print("default")

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

            }
        })
        // cancelButton.setValue(UIColor(rgb: 0xFC5757), forKey: "titleTextColor")
        alert.addAction(cancelButton)

        alert.addAction(UIAlertAction(title: "Ενεργοποίηση", style: .default, handler: { action in
            switch action.style{
                case .default:
                self.submitOrderRequest()

                case .cancel:
                print("cancel")

                case .destructive:
                print("destructive")

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

    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)
    }
    
    
    // MARK: - API CALLS
    func getProfileRequest() {
        swiftApi().getProfileAsync(getProfileCallback)
    }

    func getProfileCallback (_ profileData: swiftApi.ProfileModel?) -> Void {
        if (profileData != nil) {
            DispatchQueue.main.async {
                self.numbersList = profileData?._msisdnList ?? []
            }
        } else {
        }
    }
    
    func submitOrderRequest() {
        swiftApi().submitOrderAsync(campaign_session_uuid: "", user_msisdn: self.selectedNumber, businessService: (ccms?._businessService ?? ""), offerName: (ccms?._offerName ?? ""), productType: (ccms?._productType ?? ""), provDuration: (ccms?._provDuration ?? ""), noOfRecurrance: (ccms?._noOfRecurrance ?? ""), price: (ccms?._price ?? ""), discount: (ccms?._discount ?? ""), voiceCategory: (ccms?._voiceCategory ?? ""), dataCategory: (ccms?._dataCategory ?? ""), minsValue: (ccms?._minsValue ?? ""), dataValue: (ccms?._dataValue ?? ""), provStepValueMins: (ccms?._provStepValueMins ?? ""),
        OfferAudienceLevel: (ccms?._offerAudienceLevel ?? ""), UACIOfferTrackingCode: (ccms?._uaciOfferTrackingCode ?? ""), OFFERCODE1: (ccms?._offerCode1 ?? ""), SCORE: (ccms?._score ?? ""), ZONE: (ccms?._zone ?? ""), WAVE: (ccms?._wave ?? ""), VALIDITY: (ccms?._validity ?? ""), TREATMENT_CODE: (ccms?._treatmentCode ?? ""), ccms_session_id: (ccms?._sessionId ?? ""), notificationMessage: (ccms?._notificationMessage ?? ""),
        submitOrderCallback)
    }
    
    func submitOrderCallback (_ response: swiftApi.GenericResponseModel?) -> Void {
        if (response != nil) {
            DispatchQueue.main.async {
                if (response?.getStatus == 1) {

                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.ccms?._title ?? ""))
                    firebaseEvent.setParameter = ("type", "gift")
                    firebaseEvent.setParameter = ("successful", "true")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                    self.showDialog("Το αίτημά σου ολοκληρώθηκε επιτυχώς!","Θα ενημερωθείς άμεσα για την ενεργοποίηση του πακέτου σου.")
                    // self.postEventRequest()
                    
                } else {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.ccms?._title ?? ""))
                    firebaseEvent.setParameter = ("type", "gift")
                    firebaseEvent.setParameter = ("successful", "false")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                    self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
                }
            }
        } else {
                let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                firebaseEvent._eventName = "loyalty_offer_activated"
                firebaseEvent.setParameter = ("name", (self.ccms?._title ?? ""))
                firebaseEvent.setParameter = ("type", "gift")
                firebaseEvent.setParameter = ("successful", "false")
                SwiftEventBus.post("firebase", sender: firebaseEvent)

            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        }
    }
    
    // MARK: - Actions
    
    @IBAction func redeemButtomAction(_ sender: Any) {
        self.numbersPopupTapped(sender)
    }

}

// MARK: NumbersPopup
extension ContextualViewController: NumbersPopupDelegate {
    @objc func numbersPopupTapped(_ sender: Any) {
       let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
       let pp = storyboard.instantiateViewController(withIdentifier: "NumberPopupViewController") as! SwiftWarplyFramework.NumberPopupViewController
        pp.InitWithController(controller: self,
                              numbersList: self.numbersList,
                              sender: sender,
                              delegate: self,
                              headerText: "Επιλογή σύνδεσης")
    }
    
    func presentedPopup() {
//        Code for when popup is presented
    }
    
    func dismissedPopup() {
//        Code for when popup is dismissed
    }
    
    func optionSelected(_ option: String) {
//        Code for when option is selected
        self.selectedNumber = option
        DispatchQueue.main.async {
            self.showConfirmDialog()
        }
    }
}