UnifiedCouponBCHeaderTableViewCell.swift 15.2 KB
//
//  UnifiedCouponBCHeaderTableViewCell.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 7/4/23.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation
// import SwiftEventBus

@objc public class UnifiedCouponBCHeaderTableViewCell: UITableViewCell, UITextViewDelegate {
    @IBOutlet weak var couponImage: UIImageView!
    @IBOutlet weak var couponImageHeight: NSLayoutConstraint!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var discriptionLabel: UILabel!
    @IBOutlet weak var merchantDescrTextView: UnselectableTappableTextView!
    @IBOutlet weak var merchantDescrTextViewHeight: NSLayoutConstraint!
    @IBOutlet weak var merchantDescrTextViewTopSpace: NSLayoutConstraint!
    @IBOutlet weak var couponView: UIView!
    @IBOutlet weak var couponNumberLabel: CopyableLabel!
    @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 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 showBarcodeButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var showBarcodeButtonTopSpace: NSLayoutConstraint!
    @IBOutlet weak var showCouponsButton: UIButton!
    
    let uiscreen: CGRect = UIScreen.main.bounds

    public override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        merchantDescrTextView.delegate = self
        
        //        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.image = UIImage(named: "market_bg", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        couponImage.contentMode = .scaleAspectFill
        couponImageHeight.constant =  255 //230 // 253 // self.uiscreen.height * 0.25
        
        nameLabel.text = "Εκπτωτικό κουπόνι COSMOTE SUPERMARKET DEALS!"
        discriptionLabel.text = "Χρησιμοποίησε τον παρακάτω κωδικό και πάρε έκπτωση στα ενεργά κουπόνια προσφορών."
        
        merchantDescrTextView.text = ""
        merchantDescrTextViewTopSpace.constant = CGFloat(0)
        merchantDescrTextViewHeight.constant = CGFloat(0)
        merchantDescrTextView.isHidden = true
        
//        let merchantList:Array<swiftApi.MerchantModel> = swiftApi().getMerchantList()
        
//        for merchant in merchantList {
//            if (merchant._uuid == couponSetData?.merchant_uuid) {
//                let htmlMerchDescrText = merchant._body
//
//                if (htmlMerchDescrText != "") {
//                    merchantDescrTextView.attributedText = htmlMerchDescrText.htmlToAttributedString
//                    merchantDescrTextView.font = UIFont(name: "PFSquareSansPro-Regular", size: 17)
//                    merchantDescrTextView.textColor = UIColor(red: 0.25, green: 0.33, blue: 0.39, alpha: 1.00)
//                    merchantDescrTextView.textAlignment = .center
//                    merchantDescrTextView.isScrollEnabled = false
//                    merchantDescrTextView.isUserInteractionEnabled = true
//                    merchantDescrTextView.isEditable = false
//                    merchantDescrTextView.isSelectable = true
//                    merchantDescrTextView.dataDetectorTypes = [.link]
//
//                    merchantDescrTextView.isHidden = false
//                    merchantDescrTextViewTopSpace.constant = CGFloat(15)
//                    let targetSize = CGSize(width: merchantDescrTextView.frame.width, height: CGFloat(MAXFLOAT))
//                    merchantDescrTextViewHeight.constant = merchantDescrTextView.sizeThatFits(targetSize).height
//                }
//
//                break;
//            }
//        }
        
        
        showBarcodeButton.titleLabel?.font = UIFont(name: "PeridotPE-Bold", size: 15)
        showBarcodeButton.setTitle("Εμφάνιση barcode", for: .normal)
        showBarcodeButton.setTitleColor(UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00), for: .normal)
        showBarcodeButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        showBarcodeButton.semanticContentAttribute = .forceRightToLeft
        showBarcodeButton.tintColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, 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);
        showBarcodeButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        
        showCouponsButton.titleLabel?.font = UIFont(name: "PeridotPE-Bold", size: 15)
//        termsButton.imageView?.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
        showCouponsButton.setTitle("Εμφάνιση προσφορών", for: .normal)
        showCouponsButton.setTitleColor(UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00), for: .normal)
        showCouponsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        showCouponsButton.semanticContentAttribute = .forceRightToLeft
        showCouponsButton.tintColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 1.00)
        showCouponsButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
        showCouponsButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10);
        showCouponsButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        showCouponsButton.frame = CGRect(x: 0.0, y: 0.0, width: showCouponsButton.intrinsicContentSize.width+10, height: 40)
    }

    public override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func configureCell(coupon: swiftApi.UnifiedCouponModel?, couponsVisible: Bool) {
        
        couponView.layer.cornerRadius = 16
//        couponNumberLabel.text = ((coupon?._code != 0) ? String(coupon?._code ?? 0) : "")
        couponNumberLabel.text = coupon?._barcode ?? ""
        couponView.frame = CGRect(x: 0.0, y: 0.0, width: couponView.intrinsicContentSize.width, height: 55)
        
            
//         let activeCoupons = coupon?._coupons.filter { $0.status == 1 }
//         let activeCouponsDiscount = (activeCoupons?.reduce(0) { $0 + (Float($1.discount ?? "0") ?? 0) }) ?? 0
        
// //        discriptionLabel.text = "Χρησιμοποίησε τον παρακάτω κωδικό και πάρε έκπτωση στα ενεργά κουπόνια προσφορών αξίας " + String(activeCouponsDiscount) + "€."
        
//         // ========
//         let discrNormalText1 = "Χρησιμοποίησε τον παρακάτω κωδικό και πάρε έκπτωση στα ενεργά κουπόνια προσφορών αξίας "
//         let discrBoldText  = String(activeCouponsDiscount) + "€."

//         let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Regular", size: 16) ?? UIFont.systemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)]
//         let attrBold = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Bold", size: 16) ?? UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)]
        
//         let sumAttributedString = NSMutableAttributedString(string:discrNormalText1, attributes:attrRegular)
//         let sumBoldString = NSMutableAttributedString(string: discrBoldText, attributes:attrBold)

//         sumAttributedString.append(sumBoldString)
//         discriptionLabel.attributedText = sumAttributedString
//         // ========
        
//        let barcodeString = constructBarcode(coupon: coupon) ?? ""
        let barcodeString = coupon?._barcode ?? ""
        barcodeLabel.text = barcodeString
        
        // Uncomment if Barcode Section is active again
        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

            showBarcodeButton.isHidden = false
            showBarcodeButtonHeight.constant = 50
            showBarcodeButtonTopSpace.constant = 10

        } else {
            barcodeImageHeight.constant = 0

            showBarcodeButton.isHidden = true
            showBarcodeButtonHeight.constant = 0
            showBarcodeButtonTopSpace.constant = 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
        }
        // ===
        
        // === Hide Barcode Section
//        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.isHidden = true
        showBarcodeButtonHeight.constant = 0
        showBarcodeButtonTopSpace.constant = 0
        // ===
        
        if let earliestExpiration = coupon?._coupons.min(by: { ($0.expiration ?? "") < ($1.expiration ?? "") }) {
            expirationLabel.text = "Το κουπόνι ισχύει έως " + (earliestExpiration.expiration ?? "")
        } else {
            expirationLabel.text = ""
        }
        
        toggleCoupons(couponsVisible: couponsVisible)
        
    }

    func constructBarcode(coupon: swiftApi.UnifiedCouponModel?) -> String? {
        // EAN 13 barcode construction
//        let couponData = coupon?.couponset_data
        let couponString = coupon?._barcode ?? ""
        
        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 ""
    }
    
    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)

        // Disable `.preview` by 3D Touch and other interactions
        return false
    }
    
    func toggleBarcode(barcodeVisible: Bool) {
        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_2.png", in: MyEmptyClass.resourceBundle(), 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_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        }
    }
    
    func toggleCoupons(couponsVisible: Bool) {
        if (couponsVisible) {
            showCouponsButton.setTitle("Απόκρυψη προσφορών", for: .normal)
            showCouponsButton.setImage(UIImage(named: "ic_up_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
            showCouponsButton.frame = CGRect(x: 0.0, y: 0.0, width: showCouponsButton.intrinsicContentSize.width+10, height: 40)

        } else {
            showCouponsButton.setTitle("Εμφάνιση προσφορών", for: .normal)
            showCouponsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
            showCouponsButton.frame = CGRect(x: 0.0, y: 0.0, width: showCouponsButton.intrinsicContentSize.width+10, height: 40)
        }
    }

}