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

import UIKit
import RSBarcodes_Swift
import AVFoundation
// import SwiftEventBus

@objc public 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 barcodeLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var showBarcodeButton: UIButton!
    @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!
    @IBOutlet weak var borderViewHeight: NSLayoutConstraint!
    @IBOutlet weak var borderView2Height: NSLayoutConstraint!
    @IBOutlet weak var border1TopSpace: NSLayoutConstraint!
    @IBOutlet weak var barcodeImageTopSpace: NSLayoutConstraint!
    @IBOutlet weak var barcodeLabelTopSpace: NSLayoutConstraint!
    @IBOutlet weak var border2TopSpace: NSLayoutConstraint!
    @IBOutlet weak var mapButton: UIButton!
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    var termsVisible: Bool = false;
    var barcodeVisible: Bool = false;
    
    public var coupon: swiftApi.CouponItemModel?
    public var isFromWallet: Bool? = false
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true

        // 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
        }
        
        showBarcodeButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 16)
        showBarcodeButton.setTitle("Εμφάνιση barcode", for: .normal)
        showBarcodeButton.setTitleColor(UIColor(red: 0.25, green: 0.33, blue: 0.39, alpha: 1.00), for: .normal)
        showBarcodeButton.setImage(UIImage(named: "ic_down_dark.png", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil), for: .normal)
        showBarcodeButton.semanticContentAttribute = .forceRightToLeft
        showBarcodeButton.tintColor = UIColor(red: 0.21, green: 0.32, blue: 0.41, alpha: 1.00)
        showBarcodeButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0);
        showBarcodeButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5);
        
        expirationLabel.text = "Το κουπόνι ισχύει έως " + (coupon?.expiration ?? "")
        
        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

        mapButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 16)
        mapButton.setTitle("Δες τα καταστήματα", for: .normal)
        mapButton.setTitleColor(UIColor(red: 0.31, green: 0.62, blue: 0.18, alpha: 1.00), for: .normal)
        mapButton.backgroundColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1.00)
        mapButton.layer.cornerRadius = 12.0
        
        termsButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Regular", 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 = couponSetData?.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()
        toggleBarcode()

        // Logs
        print("Coupon: " + (coupon?.coupon ?? ""))
        print("Coupon Name: " + (couponSetData?.name ?? ""))
        print("Coupon Description: " + (couponSetData?.short_description ?? ""))
        print("Coupon Expiration: " + (coupon?.expiration ?? ""))
        
    }
    
    // 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 toggleBarcode() {
        if (barcodeVisible) {
            barcodeImage.isHidden = false
            if (barcodeImage.image == nil) {
                barcodeImageHeight.constant = CGFloat(0)
            } else {
                barcodeImageHeight.constant = self.uiscreen.height * 0.1
            }
            barcodeLabel.isHidden = false
            let targetSize = CGSize(width: barcodeLabel.frame.width, height: CGFloat(MAXFLOAT))
            barcodeLabelHeight.constant = barcodeLabel.sizeThatFits(targetSize).height
            
            borderViewHeight.constant = CGFloat(1)
            borderView2Height.constant = CGFloat(1)
            
            border1TopSpace.constant = CGFloat(20) // 20
            barcodeImageTopSpace.constant = CGFloat(10) // 10
            barcodeLabelTopSpace.constant = CGFloat(10) // 10
            border2TopSpace.constant = CGFloat(15) // 15
            
            showBarcodeButton.setTitle("Απόκρυψη barcode", for: .normal)
            showBarcodeButton.setImage(UIImage(named: "ic_up_dark.png", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil), for: .normal)
            
        } else {
            barcodeImage.isHidden = true
            barcodeImageHeight.constant = CGFloat(0)
            barcodeLabel.isHidden = true
            barcodeLabelHeight.constant = CGFloat(0)
            
            borderViewHeight.constant = CGFloat(0)
            borderView2Height.constant = CGFloat(0)
            
            border1TopSpace.constant = CGFloat(0) // 20
            barcodeImageTopSpace.constant = CGFloat(0) // 10
            barcodeLabelTopSpace.constant = CGFloat(0) // 10
            border2TopSpace.constant = CGFloat(0) // 15
            
            showBarcodeButton.setTitle("Εμφάνιση barcode", for: .normal)
            showBarcodeButton.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;
                fixedCouponCode = fixedCouponCode + zerosStr;
            }

            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) {
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
        let vc = storyboard.instantiateViewController(withIdentifier: "ShareViewController") as! SwiftWarplyFramework.ShareViewController
        vc.coupon = self.coupon
        vc.isFromWallet = self.isFromWallet
        self.navigationController?.pushViewController(vc, animated: true)
    }

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

    @IBAction func mapButtonAction(_ sender: Any) {
        // TODO: open MapVC
    }
}