CouponBarcodeViewController.swift 6.63 KB
//
//  CouponBarcodeViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 20/5/22.
//

import UIKit
//import WarplySDKFrameworkIOS
import RSBarcodes_Swift
import AVFoundation

@objc class CouponBarcodeViewController: UIViewController {
    @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 discriptionLabel: UILabel!
    @IBOutlet weak var couponView: UIView!
    @IBOutlet weak var couponNumberLabel: UILabel!
    @IBOutlet weak var barcodeImage: UIImageView!
    @IBOutlet weak var barcodeImageHeight: NSLayoutConstraint!
    @IBOutlet weak var barcodeLabel: UILabel!
    @IBOutlet weak var expirationLabel: UILabel!
    @IBOutlet weak var redeemButton: UIButton!
    @IBOutlet weak var termsButton: UIButton!
    @IBOutlet weak var termsTextView: UITextView!
    @IBOutlet weak var termsTextViewHeight: NSLayoutConstraint!
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    var termsVisible: Bool = false;
    
    var coupon: swiftApi.CouponItemModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 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
        
        //        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 = self.uiscreen.height * 0.25
        
        nameLabel.text = couponSetData?.name ?? ""
        discriptionLabel.text = couponSetData?.short_description ?? ""
        
        couponView.layer.cornerRadius = 10
        couponNumberLabel.text = coupon?.coupon ?? ""
        
        let barcodeString = constructBarcode() ?? ""
        barcodeLabel.text = barcodeString

        if let barcodeUIImage = RSUnifiedCodeGenerator.shared.generateCode(barcodeString, machineReadableCodeObjectType: AVMetadataObject.ObjectType.ean13.rawValue, targetSize: CGSize(width: self.uiscreen.width * 0.8, height: self.uiscreen.height * 0.1)) {
            barcodeImage.image = barcodeUIImage
            
            barcodeImageHeight.constant = self.uiscreen.height * 0.1
        } else {
            barcodeImageHeight.constant = 0
        }
        
        expirationLabel.text = "Το κουπόνι ισχύει έως " + (coupon?.expiration ?? "")
        
        redeemButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        
        termsButton.titleLabel?.font = .systemFont(ofSize: 15.0, weight: .semibold)
//        termsButton.imageView?.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
        
        let htmlText = couponSetData?.terms ?? ""
        termsTextView.attributedText = htmlText.htmlToAttributedString
        termsTextView.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        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 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 constructBarcode() -> String? {
        // EAN 13 barcode construction
        let couponData = coupon?.couponset_data
        let couponString = coupon?.coupon ?? ""
        
        if (!couponString.isEmpty) {
            var checkDigit = 0;
            var result = 0;
            
            var fixedCouponCode = couponString;
            if (fixedCouponCode.count < 12) {
                let loops = 12 - fixedCouponCode.count;
                var zerosStr = "";
                for i in 0 ..< loops {
                    zerosStr += "0"
                }
                fixedCouponCode = zerosStr + fixedCouponCode;
            }

            var multiplier = 3;
            for idx in (0 ... (fixedCouponCode.count - 1)).reversed() {
                let curChar = fixedCouponCode[idx];
                result += (Int(curChar) ?? 0) * multiplier;
                multiplier = multiplier == 3 ? 1 : 3;
            }
            checkDigit = 10 - (result % 10);

            let barcodeStr = fixedCouponCode + String(checkDigit);
            return barcodeStr;
        }

        return ""
    }
    
    // MARK: - Actions
    
    @IBAction func redeemButtomAction(_ sender: Any) {
        // TODO: Add redeem action
        
        let alert = UIAlertController(title: "Το κουπόνι σου ενεργοποιήθηκε", message: "Μπορείς να το βρεις στην αρχική οθόνη της εφαρμογής και στην ενότητα ενεργά δώρα!", 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)
    }
    
    @IBAction func termsButtonAction(_ sender: Any) {
        termsVisible = !termsVisible
        toggleTerms()
    }
}