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

import UIKit
import SwiftEventBus

@objc public class CouponViewController: UIViewController {
    @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 termsButton: UIButton!
    @IBOutlet weak var termsTextView: UITextView!
    @IBOutlet weak var termsTextViewHeight: NSLayoutConstraint!

    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?
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true

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

        // if ((profile != nil) && (profile?._nonTelco == true)) {
        if (swiftApi().getUserNonTelco() == true) {
            nonTelcoDialog("", "Παρακαλούμε πολύ πρόσθεσε τις συνδέσεις σου στην COSMOTE για να έχεις πρόσβαση στα προνόμια του νέου Loyalty προγράμματος της COSMOTE!");
        }
        
        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
        
        couponImage.load(link: couponset?.img_preview ?? "", placeholder: UIImage(), cache: URLCache())
        couponImage.contentMode = .scaleAspectFill
        couponImageHeight.constant = self.uiscreen.height * 0.25

        nameLabel.text = couponset?.name ?? ""
        let htmlDescrText = couponset?.description ?? ""
        descriptionLabel.text = htmlDescrText.htmlToString
        
        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
        
        termsButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 16)
//        termsButton.imageView?.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
        termsButton.setTitle("Όροι χρήσης", for: .normal)
        termsButton.setTitleColor(UIColor(red: 0.25, green: 0.33, blue: 0.39, alpha: 1.00), for: .normal)
        termsButton.setImage(UIImage(named: "ic_down_dark.png", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil), for: .normal)
        termsButton.semanticContentAttribute = .forceRightToLeft
        termsButton.tintColor = UIColor(red: 0.21, green: 0.32, blue: 0.41, 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);
        
        let htmlText = couponset?.terms ?? ""
        termsTextView.attributedText = htmlText.htmlToAttributedString
        termsTextView.font = UIFont(name: "PFSquareSansPro-Regular", size: 15)
        termsTextView.textColor = UIColor(red: 0.25, green: 0.33, blue: 0.39, alpha: 1.00)
        termsTextView.textAlignment = .center
        termsTextView.isScrollEnabled = false
        
        toggleTerms()
        
    }
    
    // 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.png", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil), for: .normal)
        } else {
            termsTextView.isHidden = true
            termsTextViewHeight.constant = CGFloat(0)
            
            termsButton.setImage(UIImage(named: "ic_down_dark.png", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil), for: .normal)
        }
    }

    func redeemCouponSetRequest(uuid: String, communication_uuid: String) {
        if (ccms == nil) {
            swiftApi().redeemCouponSetAsync(uuid: uuid, communication_uuid: communication_uuid, redeemCouponSetCallback)
        } 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)
        }
    }
    
    func redeemCouponSetCallback (_ response: swiftApi.GenericResponseModel?) -> Void {
        if (response != nil) {
            DispatchQueue.main.async {
                if (response?.getStatus == 1) {
                    self.showSuccessDialog("Το κουπόνι σου ενεργοποιήθηκε","Μπορείς να το βρεις στην αρχική οθόνη της εφαρμογής και στην ενότητα ενεργά δώρα!")
                    
                    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 {
                            }
                        } else {
                        }
                    }
                } else if (response?.getStatus == 3) {
                    self.showDialog("Αποτυχία","Το κουπόνι δεν είναι διαθέσιμο για αγορά")
                } else if (response?.getStatus == 5) {
                    self.showDialog("Αποτυχία","Δεν έχεις αρκετούς πόντους")
                } else {
                    self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
                }
            }
        } else {
            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)

        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()
    }
}