CouponViewController.swift 19.5 KB
//
//  CouponViewController.swift
//  WarplySDKFrameworkIOS
//
//  Created by Manos Chorianopoulos on 5/5/22.
//

import UIKit
import SwiftEventBus

@objc public class CouponViewController: UIViewController, UITextViewDelegate {
    @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 descriptionTextView: UnselectableTappableTextView!
    @IBOutlet weak var descriptionTextViewHeight: NSLayoutConstraint!
    @IBOutlet weak var redeemButton: UIButton!
    @IBOutlet weak var termsButton: UIButton!
    @IBOutlet weak var termsTextView: UnselectableTappableTextView!
    @IBOutlet weak var termsTextViewHeight: NSLayoutConstraint!
    @IBOutlet weak var topBorderLine: UIImageView!
    
    public var ccms: swiftApi.LoyaltyContextualOfferModel?
    public var profile:swiftApi.ProfileModel? = swiftApi().getConsumer()
    
    let uiscreen: CGRect = UIScreen.main.bounds

    var termsVisible: Bool = false;

    public var couponset: swiftApi.CouponSetItemModel?
    public var campaign: swiftApi.CampaignItemModel?

    let spinner = SpinnerViewController()
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true
        descriptionTextView.delegate = self
        termsTextView.delegate = self

        // Do any additional setup after loading the view.
        setBackButton()
        setNavigationTitle("Εκπτωτικό κουπόνι")

        // if ((profile != nil) && (profile?._nonTelco == true)) {
        if (swiftApi().getUserNonTelco() == true) {
            nonTelcoDialog("Αδυναμία ενεργοποίησης", "Πρόσθεσε σύνδεση COSMOTE σταθερής, κινητής ή TV για να έχεις πρόσβαση στις προσφορές.");
        }
        
        backgroundImage.image = UIImage(named: "coupons_scrollview_white", in: MyEmptyClass.resourceBundle(), 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: MyEmptyClass.resourceBundle(), compatibleWith: nil)!
//        var aspectR: CGFloat = 0.0
//
//        aspectR = image.size.width/image.size.height
//
//        topBorderLine.translatesAutoresizingMaskIntoConstraints = false
//        topBorderLine.image = image
//        topBorderLine.contentMode = .scaleAspectFill
//
//        NSLayoutConstraint.activate([
//            topBorderLine.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 0),
//            topBorderLine.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 0),
//            topBorderLine.trailingAnchor.constraint(equalTo: mainView.trailingAnchor, constant: 0),
//            topBorderLine.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width),
//            topBorderLine.heightAnchor.constraint(equalTo: topBorderLine.widthAnchor, multiplier: 1/aspectR)
//        ])
        
        couponImage.load(link: couponset?.img_preview ?? "", placeholder: UIImage(), cache: URLCache())
        couponImage.contentMode = .scaleAspectFill
        couponImageHeight.constant =  255 //230 // 253 // self.uiscreen.height * 0.25

        nameLabel.text = couponset?.name ?? ""
        let htmlDescrText = couponset?.description ?? ""
        
        descriptionTextView.attributedText = htmlDescrText.htmlToAttributedString
        descriptionTextView.font = UIFont(name: "PeridotPE-Regular", size: 16)
        descriptionTextView.textColor = UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)
        descriptionTextView.textAlignment = .center
        descriptionTextView.isScrollEnabled = false
        descriptionTextView.isUserInteractionEnabled = true
        descriptionTextView.isEditable = false
        descriptionTextView.isSelectable = true
        descriptionTextView.dataDetectorTypes = [.link]
        
        let targetSize = CGSize(width: descriptionTextView.frame.width, height: CGFloat(MAXFLOAT))
        descriptionTextViewHeight.constant = descriptionTextView.sizeThatFits(targetSize).height
        
        redeemButton.setTitle("Απόκτησέ το", for: .normal)
        redeemButton.setTitleColor(.white, for: .normal)
        redeemButton.backgroundColor = UIColor(red: 0.05, green: 0.65, blue: 0.00, alpha: 1.00)
        redeemButton.layer.cornerRadius = 16.0
        redeemButton.frame = CGRect(x: 0.0, y: 0.0, width: redeemButton.intrinsicContentSize.width, height: 50)
        redeemButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: 25)
        // Fix width for ipad
        if UIDevice.current.userInterfaceIdiom == .pad {
             // iPad
            redeemButton.titleLabel?.font = UIFont(name: "PeridotPE-SBold", size: 19)
//            redeemButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
         } else {
             // not iPad (iPhone, mac, tv, carPlay, unspecified)
             redeemButton.titleLabel?.font = UIFont(name: "PeridotPE-SBold", size: 17)
//             redeemButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.6).isActive = true
         }
        
        termsButton.titleLabel?.font = UIFont(name: "PeridotPE-Bold", size: 15)
//        termsButton.imageView?.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
        termsButton.setTitle("Όροι χρήσης", for: .normal)
        termsButton.setTitleColor(UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00), for: .normal)
        termsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        termsButton.semanticContentAttribute = .forceRightToLeft
        termsButton.tintColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 1.00)
        termsButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0);
        termsButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5);
        termsButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        
        let htmlText = couponset?.terms ?? ""
        termsTextView.attributedText = htmlText.htmlToAttributedString
        termsTextView.font = UIFont(name: "PeridotPE-Regular", size: 14)
        termsTextView.textColor = UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)
        termsTextView.textAlignment = .left
        termsTextView.isScrollEnabled = false
        termsTextView.isUserInteractionEnabled = true
        termsTextView.isEditable = false
        termsTextView.isSelectable = true
        termsTextView.dataDetectorTypes = [.link]
        
        toggleTerms()
        
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "CouponsetScreen")
        
        self.navigationController?.hideHairline()
    }
    
    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)

        // Disable `.preview` by 3D Touch and other interactions
        return false
    }
    
    // MARK: - Functions
    func nonTelcoDialog(_ 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 toggleTerms() {
        if (termsVisible) {
            termsTextView.isHidden = false
            let targetSize = CGSize(width: termsTextView.frame.width, height: CGFloat(MAXFLOAT))
            termsTextViewHeight.constant = termsTextView.sizeThatFits(targetSize).height
            
            termsButton.setImage(UIImage(named: "ic_up_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        } else {
            termsTextView.isHidden = true
            termsTextViewHeight.constant = CGFloat(0)
            
            termsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        }
    }

    func showSpinner() {
        // add the spinner view controller
        // addChild(spinner)
        // spinner.view.frame = view.frame
        // view.addSubview(spinner.view)
        // spinner.didMove(toParent: self)

        addChild(spinner)
        spinner.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
        self.view.addSubview(spinner.view)
        spinner.didMove(toParent: self)
    }
    
    func hideSpinner() {
        // remove the spinner view controller
        spinner.willMove(toParent: nil)
        spinner.view.removeFromSuperview()
        spinner.removeFromParent()
    }

    func redeemCouponSetRequest(uuid: String, communication_uuid: String) {
        showSpinner()

        if (ccms == nil) {
            swiftApi().redeemCouponSetAsync(uuid: uuid, communication_uuid: communication_uuid, redeemCouponSetCallback, failureCallback: {errorCode in
                self.hideSpinner()
                
                let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                firebaseEvent._eventName = "loyalty_offer_activated"
                firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                firebaseEvent.setParameter = ("type", "coupon")
                firebaseEvent.setParameter = ("successful", "false")
                SwiftEventBus.post("firebase", sender: firebaseEvent)

                self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
            })
        } else {
            // TODO: MAybe change user_msisdn: profile?._msisdn ?? ""
            swiftApi().redeemCouponSetAsync(uuid: uuid, communication_uuid: communication_uuid, user_msisdn: profile?._msisdn ?? "", 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 ?? ""), redeemCouponSetCallback, failureCallback: {errorCode in
                self.hideSpinner()
                
                let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                firebaseEvent._eventName = "loyalty_offer_activated"
                firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                firebaseEvent.setParameter = ("type", "coupon")
                firebaseEvent.setParameter = ("successful", "false")
                SwiftEventBus.post("firebase", sender: firebaseEvent)

                self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
            })
        }
    }
    
    func redeemCouponSetCallback (_ response: swiftApi.GenericResponseModel?) -> Void {
        hideSpinner()
        
        if (response != nil) {
            DispatchQueue.main.async {
                if (response?.getStatus == 1) {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                    firebaseEvent.setParameter = ("type", "coupon")
                    firebaseEvent.setParameter = ("successful", "true")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                    if (self.ccms != nil) {
                        let ccmsEnabled = swiftApi.WarplyCCMSEnabledModel()
                        ccmsEnabled._isActivated = true
                        SwiftEventBus.post("ccms_enabled", sender: ccmsEnabled)
                    }

                    self.showSuccessDialog("Επιτυχής ενεργοποίηση","Το κουπόνι σου έχει ενεργοποιηθεί στην ενότητα My Rewards.")
                    
                    swiftApi().getCouponsAsync(getCouponsCallback, failureCallback: {errorCode in })
                    swiftApi().getCampaignsAsyncNew(language: "en", filters: [String : Any](), getCampaignsCallback, failureCallback: {errorCode in })
                    
                    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 (response?.getStatus == 3) {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                    firebaseEvent.setParameter = ("type", "coupon")
                    firebaseEvent.setParameter = ("successful", "false")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                    self.showDialog("Αποτυχία","Το κουπόνι δεν είναι διαθέσιμο για αγορά")

                } else if (response?.getStatus == 5) {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                    firebaseEvent.setParameter = ("type", "coupon")
                    firebaseEvent.setParameter = ("successful", "false")
                    SwiftEventBus.post("firebase", sender: firebaseEvent)

                    self.showDialog("Αποτυχία","Δεν έχεις αρκετούς πόντους")

                } else if (response?.getStatus == 6) {
                    let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                    firebaseEvent._eventName = "loyalty_offer_activated"
                    firebaseEvent.setParameter = ("name", (self.couponset?.name ?? ""))
                    firebaseEvent.setParameter = ("type", "coupon")
                    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.couponset?.name ?? ""))
                    firebaseEvent.setParameter = ("type", "coupon")
                    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.couponset?.name ?? ""))
            firebaseEvent.setParameter = ("type", "coupon")
            firebaseEvent.setParameter = ("successful", "false")
            SwiftEventBus.post("firebase", sender: firebaseEvent)

            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        }
    }

    func showSuccessDialog(_ 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)
                
                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: - Actions
    
    @IBAction func redeemButtomAction(_ sender: Any) {
//        SwiftEventBus.post("couponRedeem", sender: coupon)
        
        swiftApi().logTrackersEvent("click", ("RetrieveCoupon:" + (couponset?.uuid ?? "")))

        redeemCouponSetRequest(uuid: couponset?.uuid ?? "", communication_uuid: campaign?.session_uuid ?? "")
        
        // let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
        // let vc = storyboard.instantiateViewController(withIdentifier: "MakeItAPresentViewController") as! SwiftWarplyFramework.MakeItAPresentViewController
        // self.navigationController?.pushViewController(vc, animated: true)
    }

    @IBAction func termsButtonAction(_ sender: Any) {
        termsVisible = !termsVisible
        toggleTerms()
    }
}