ShareViewController.swift 14 KB
//
//  ShareViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 15/7/22.
//

import UIKit
import SwiftEventBus

@objc public class ShareViewController: UIViewController, UITextFieldDelegate, UIPopoverControllerDelegate {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var mainViewBottom: NSLayoutConstraint!
    @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 senderLabel: UILabel!
    @IBOutlet weak var senderArrowImage: UIImageView!
    @IBOutlet weak var senderButton: UIButton!
    @IBOutlet weak var numberTextField: UITextField!
    @IBOutlet weak var redeemButton: UIButton!
    @IBOutlet weak var topBorderLine: UIImageView!
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    public var coupon: swiftApi.CouponItemModel?
    public var isFromWallet: Bool? = false
    var selectedNumber: String = ""
    var numbersList: Array<String> = []
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true
        
        NotificationCenter.default.addObserver(self,
               selector: #selector(self.keyboardNotification(notification:)),
               name: UIResponder.keyboardWillChangeFrameNotification,
               object: nil)
        
        self.setupToHideKeyboardOnTapOnView()
        numberTextField.delegate = self
        
        getProfileRequest()

        // Do any additional setup after loading the view.
        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 = .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)
        ])
        
        //        COUPONSET: desc, img_preview, name, terms
        //        COUPON: coupon, expiration, discount, status
                
        let couponSetData: swiftApi.CouponSetItemModel? = coupon?.couponset_data
        
        couponImage.load(link: couponSetData?.img_preview ?? "", placeholder: UIImage(), cache: URLCache())
        couponImage.contentMode = .scaleAspectFill
        couponImageHeight.constant = 230 // 253 // self.uiscreen.height * 0.25
        
        nameLabel.text = couponSetData?.name ?? ""
        // descriptionLabel.text = couponSetData?.short_description ?? ""
        descriptionLabel.text = "Επίλεξε το κινητό από το οποίο θα γίνει η αποστολή και συμπλήρωσε το COSMOTE κινητό που θα λάβει το δώρο."
        
        senderLabel.text = "Αποστολέας"
        senderArrowImage.image = UIImage(named: "ic_down_dark", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        
        senderButton.addTarget(self, action: #selector(self.numbersPopupTapped(_:)), for: .touchUpInside)
        
        numberTextField.font = UIFont(name: "PFSquareSansPro-Regular", size: 16)
        numberTextField.textColor = UIColor(red: 0.25, green: 0.33, blue: 0.39, alpha: 1.00)
        numberTextField.attributedPlaceholder = NSAttributedString(string: "Καταχώρηση τηλεφώνου", attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 0.68, green: 0.68, blue: 0.68, alpha: 1.00)])
        numberTextField.keyboardType = .asciiCapableNumberPad
        numberTextField.addDoneButtonOnKeyboard()
        
        redeemButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 18)
        redeemButton.setTitle("Αποστολή με SMS", 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 = 8.0
        redeemButton.frame = CGRect(x: 0.0, y: 0.0, width: redeemButton.intrinsicContentSize.width, height: 44)
        redeemButton.contentEdgeInsets = UIEdgeInsets(top: 1, left: 16, bottom: 0, right: 16)
        // Fix width for ipad
//        if UIDevice.current.userInterfaceIdiom == .pad {
//             // iPad
//            redeemButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
//         } else {
//             // not iPad (iPhone, mac, tv, carPlay, unspecified)
//             redeemButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.6).isActive = true
//         }
       
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "CouponShareScreen")
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func keyboardNotification(notification: NSNotification) {
          guard let userInfo = notification.userInfo else { return }

          let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
          let endFrameY = endFrame?.origin.y ?? 0
          let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
          let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
          let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
          let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)

          if endFrameY >= UIScreen.main.bounds.size.height {
            self.mainViewBottom?.constant = 0.0
          } else {
            self.mainViewBottom?.constant = endFrame?.size.height ?? 0.0
          }

          UIView.animate(
            withDuration: duration,
            delay: TimeInterval(0),
            options: animationCurve,
            animations: { self.view.layoutIfNeeded() },
            completion: nil)
    }
    
    // MARK: - Functions
    func showSendDialog() -> 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:
                let couponSetData: swiftApi.CouponSetItemModel? = self.coupon?.couponset_data
                let couponName = couponSetData?.name ?? ""
                swiftApi().logTrackersEvent("click", ("ShareCoupon:" + couponName))
                self.cosmoteCouponSharingRequest()

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

    func showDialogWithBack(_ 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 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:
                if (self.isFromWallet == true) {
                    self.popBack(3)
                } else {
                    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 ?? []
                
                print("========= getProfileRequest SUCCESSSS =========")
            }
        } else {
            print("========= getProfileRequest ERROR =========")
        }
    }

    func cosmoteCouponSharingRequest() {
        swiftApi().cosmoteCouponSharingAsync(coupon: coupon?.coupon ?? "", sender: selectedNumber, receiver: numberTextField.text ?? "", couponSharingCallback)
    }
    
    func couponSharingCallback (_ response: swiftApi.GenericResponseModel?) -> Void {
        if (response != nil) {
            DispatchQueue.main.async {
                if (response?.getStatus == 1) {
                    
                   swiftApi().getCouponsAsync(getCouponsCallback)

                   func getCouponsCallback (_ couponsData: Array<swiftApi.CouponItemModel>?) -> Void {
                       if (couponsData != nil) {

                           DispatchQueue.main.async {
                            SwiftEventBus.post("coupons_fetched")
                            self.showSuccessDialog("Συγχαρητήρια!","Μόλις έκανες δώρο ένα κουπόνι!")
                           }
                       } else {
                       }
                   }
                } else if (response?.getStatus == 4) {
                    self.showDialog("Αποτυχία", response?.getMsg ?? "")
                    
                } else {
                    self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
                }
            }
        } else {
            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        }
    }
    
    // MARK: - Actions
    @IBAction func redeemButtomAction(_ sender: Any) {
        if (selectedNumber == "" || numberTextField.text == "") {
            self.showDialog("Αποτυχία αποστολής","Παρακαλούμε συμπλήρωσε σωστά τα πεδία.")
        } else {
            self.showSendDialog()
        }
    }
    
}

// MARK: NumbersPopup
extension ShareViewController: NumbersPopupDelegate {
    @objc func numbersPopupTapped(_ sender: Any) {
        if (self.numbersList.count == 0) {
            self.showDialogWithBack("Κάνε δώρο","Για την αποστολή του δώρου σου χρειάζεται να έχεις κινητό COSMOTE.")
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            // self.storyboard?
            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
        selectedNumber = option
        senderLabel.text = option
    }
}