ShareViewController.swift 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
//
//  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> = []
    
    let spinner = SpinnerViewController()
    
    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("Δώρισέ το")
        
        // Temporarily disable the table view's accessibility to prevent immediate focus shift
        self.mainView.accessibilityElementsHidden = true
        
        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)
//        ])
        
        //        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 =  222 // 255 //230 // 253 // self.uiscreen.height * 0.25
        
        nameLabel.text = couponSetData?.name ?? ""
        // descriptionLabel.text = couponSetData?.short_description ?? ""
        descriptionLabel.text = "Επίλεξε το κινητό από το οποίο θα γίνει η αποστολή και συμπλήρωσε το COSMOTE κινητό που θα λάβει το δώρο."
        
        senderLabel.text = "Αποστολέας"
        senderLabel.textColor = UIColor(red: 0.52, green: 0.52, blue: 0.52, alpha: 1.00)
        senderArrowImage.image = UIImage(named: "ic_down_dark_2", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        
        senderButton.addTarget(self, action: #selector(self.numbersPopupTapped(_:)), for: .touchUpInside)
        
        numberTextField.font = UIFont(name: "PeridotPE-Regular", size: 16)
        numberTextField.textColor = UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)
        numberTextField.attributedPlaceholder = NSAttributedString(string: "Καταχώρηση τηλεφώνου", attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 0.52, green: 0.52, blue: 0.52, alpha: 1.00)])
        numberTextField.keyboardType = .asciiCapableNumberPad
        numberTextField.addDoneButtonOnKeyboard()
        
        redeemButton.titleLabel?.font = UIFont(name: "PeridotPE-SBold", size: 17)
        redeemButton.setTitle("Αποστολή με SMS", 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.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
//         }
       
        setupAccessibilty()
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "CouponShareScreen")
        
        self.navigationController?.hideHairline()
    }
    
    public override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

//        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            UIAccessibility.post(notification: .screenChanged, argument: self.navigationItem.titleView)
//        }
        
        // Re-enable table view accessibility after the announcement
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.mainView.accessibilityElementsHidden = false
        }
    }
    
    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 setupAccessibilty () {
        couponImage.isAccessibilityElement = true
        couponImage.accessibilityLabel = "Φωτογραφία εκπτωτικού κουπονιού"
        couponImage.accessibilityTraits = .image
        
        senderButton.isAccessibilityElement = true
        senderButton.accessibilityLabel = (senderLabel.text ?? "Αποστολέας") + ": " + selectedNumber
        senderButton.accessibilityHint = "Διπλό πάτημα για άνοιγμα"
        senderButton.accessibilityTraits = .button
        
        redeemButton.isAccessibilityElement = true
        redeemButton.accessibilityLabel = redeemButton.title(for: .normal)
        redeemButton.accessibilityHint = "Διπλό πάτημα για άνοιγμα"
        redeemButton.accessibilityTraits = .button
    }
    
    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 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, failureCallback: {errorCode in
            print("========= getProfileRequest ERROR =========")
        })
    }

    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() {
        self.showSpinner()
        swiftApi().cosmoteCouponSharingAsync(coupon: coupon?.coupon ?? "", sender: selectedNumber, receiver: numberTextField.text ?? "", couponSharingCallback, failureCallback: {errorCode in
            self.hideSpinner()
            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        })
    }
    
    func couponSharingCallback (_ response: swiftApi.GenericResponseModel?) -> Void {
        self.hideSpinner()
        if (response != nil) {
            DispatchQueue.main.async {
                if (response?.getStatus == 1) {
                    self.showSuccessDialog("Συγχαρητήρια!","Μόλις έκανες δώρο ένα κουπόνι!")

                    if let tempCoupon = self.coupon {
                        swiftApi().removeCouponItem(couponArg: tempCoupon)
                        SwiftEventBus.post("coupons_fetched")
                    }
                    
                    // swiftApi().getCouponsAsync(getCouponsCallback, failureCallback: {errorCode in })

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

                //            DispatchQueue.main.async {
                //             SwiftEventBus.post("coupons_fetched")
                //            }
                //        } 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
        senderLabel.textColor = UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)
        
        senderButton.accessibilityLabel = "Αποστολέας: " + selectedNumber
    }
}