MarketPassViewController.swift 14.5 KB
//
//  MarketPassViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 14/1/25.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation

@objc public class MarketPassViewController: UIViewController {
    @IBOutlet weak var passContainerView: UIView!
    @IBOutlet weak var passTitleLabel: UILabel!
    @IBOutlet weak var passSubtitleLabel: UILabel!
    @IBOutlet weak var barcodeView: UIView!
    @IBOutlet weak var barcodeImage: UIImageView!
    @IBOutlet weak var barcodeImageHeight: NSLayoutConstraint!
    @IBOutlet weak var barcodeLabel: UILabel!
    @IBOutlet weak var couponsValueLabel: UILabel!
    @IBOutlet weak var smLogosView: UIView!
    @IBOutlet weak var mapButton: UIButton!
    
    var marketPassDetails:swiftApi.MarketPassDetailsModel?
    
    let spinner = SpinnerViewController()
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true
        
        passContainerView.isHidden = true
        getMarketPassDetailsRequest()
        
        setBackButton()
        setNavigationTitle("SUPERMARKET DEALS")
        // Setup the info button with an action
        setNavBarRightInfoButton() {
            // This closure is the action that will be executed when the info button is tapped
            
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
            let vc = storyboard.instantiateViewController(withIdentifier: "MarketPassInfoViewController") as! SwiftWarplyFramework.MarketPassInfoViewController
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        setupUI()
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "MarketPassScreen")
        
        self.navigationController?.hideHairline()
    }

    // MARK: - Functions
    func setupUI() {
        passContainerView.backgroundColor = UIColor(rgb: 0x36B32B)
        passContainerView.layer.cornerRadius = 16.0
        // Add shadow
        passContainerView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.31).cgColor
        passContainerView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        passContainerView.layer.shadowOpacity = 1.0
        passContainerView.layer.shadowRadius = 3.0
        
        passTitleLabel.text = "SUPERMARKET DEALS CARD"
//        passTitleLabel.font = UIFont(name: "BTCosmo-Bold", size: 23)
        passTitleLabel.font = UIFont(name: "BTCosmo-Bold", size: 22)
        passTitleLabel.textColor = .white
        
        passSubtitleLabel.text = "Χρησιμοποίησε τον κωδικό σου και κέρδισε έκπτωση στις αγορές σου!"
        passSubtitleLabel.font = UIFont(name: "PeridotPE-Regular", size: 17.0)
        passSubtitleLabel.textColor = .white
        
        barcodeView.backgroundColor = .white
        barcodeView.layer.cornerRadius = 16.0
        barcodeView.layer.borderWidth = 2
        barcodeView.layer.borderColor = UIColor(rgb: 0xDADDE4).cgColor
        
        let barcodeString = ""
        barcodeLabel.text = barcodeString
        barcodeLabel.font = UIFont(name: "PeridotPE-Regular", size: 19.0)
        barcodeLabel.textColor = UIColor(rgb: 0x212121)
        
//         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.12)) {
// //        if let barcodeUIImage = RSUnifiedCodeGenerator.shared.generateCode(barcodeString, machineReadableCodeObjectType: AVMetadataObject.ObjectType.ean13.rawValue, targetSize: CGSize(width: 110, height: 83)) {
//             barcodeImage.image = barcodeUIImage

//             barcodeImageHeight.constant = self.uiscreen.height * 0.12
// //            barcodeImageHeight.constant = 83

//         } else {
//             barcodeImageHeight.constant = 0
//         }
        
        // TODO: FIX
        // let couponsValueString = "30"
        // let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Regular", size: 17) ?? UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]
        // let attrBold = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Bold", size: 17) ?? UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]
        
        // let couponsValueNormalText1 = "Έχεις κουπόνια συνολικής αξίας "
        // let couponsValueBoldText  = couponsValueString + "€"

        // let couponsValueAttributedString = NSMutableAttributedString(string:couponsValueNormalText1, attributes:attrRegular)
        // let couponsValueBoldString = NSMutableAttributedString(string: couponsValueBoldText, attributes:attrBold)

        // couponsValueAttributedString.append(couponsValueBoldString)
        // couponsValueLabel.attributedText = couponsValueAttributedString
        
        mapButton.titleLabel?.font = UIFont(name: "PeridotPE-SBold", size: 16)
        mapButton.setTitle("Δες στο χάρτη", for: .normal)
        mapButton.setTitleColor(UIColor(rgb: 0x006D26), for: .normal)
        mapButton.layer.cornerRadius = 10.0
        mapButton.frame = CGRect(x: 0.0, y: 0.0, width: 148, height: 48)
//        mapButton.frame = CGRect(x: 0.0, y: 0.0, width: mapButton.intrinsicContentSize.width, height: 55)
//        mapButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: 25)
        mapButton.backgroundColor = .clear
        mapButton.layer.borderWidth = 2
        mapButton.layer.borderColor = UIColor(rgb: 0x006D26).cgColor
        
        smLogosView.layer.cornerRadius = 16.0
        smLogosView.layer.maskedCorners = [ .layerMinXMaxYCorner, .layerMaxXMaxYCorner] // Bottom left, right corner radius
        
        // TODO: FIX - Replace with dynamic images
//         let imageNames = ["active_code_logo_2", "active_code_logo_2", "active_code_logo_2"]
// //        let images = imageNames.compactMap { UIImage(named: $0) }
//         let images = imageNames.compactMap { UIImage(named: $0, in: MyEmptyClass.resourceBundle(), compatibleWith: nil) }
        
//         // Create a horizontal stack view
//         let stackView = UIStackView()
//         stackView.axis = .horizontal
//         stackView.spacing = 15 // Spacing between images
//         stackView.alignment = .center
//         stackView.distribution = .equalSpacing
        
//         // Add UIImageViews to the stack view
//         for image in images {
//             let imageView = UIImageView(image: image)
//             imageView.contentMode = .scaleAspectFit
//             imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true // Set a width
//             imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true // Set a height
//             stackView.addArrangedSubview(imageView)
//         }
        
//         // Add the stack view to your main view
//         smLogosView.addSubview(stackView)
        
//         // Set up constraints for the stack view
//         stackView.translatesAutoresizingMaskIntoConstraints = false
//         NSLayoutConstraint.activate([
//             stackView.leadingAnchor.constraint(equalTo: smLogosView.leadingAnchor, constant: 25),
//             stackView.centerYAnchor.constraint(equalTo: smLogosView.centerYAnchor),
//         ])
    }

    func updateUI() {
//        let barcodeString = constructBarcode(coupon: marketPassDetails?._barcode) ?? ""
       let barcodeString = marketPassDetails?._barcode ?? ""
        barcodeLabel.text = barcodeString
        barcodeLabel.frame.size.width = barcodeLabel.intrinsicContentSize.width
        barcodeLabel.frame.size.height = barcodeLabel.intrinsicContentSize.height
        
        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.12)) {
//        if let barcodeUIImage = RSUnifiedCodeGenerator.shared.generateCode(barcodeString, machineReadableCodeObjectType: AVMetadataObject.ObjectType.ean13.rawValue, targetSize: CGSize(width: 110, height: 83)) {
            barcodeImage.image = barcodeUIImage

            barcodeImageHeight.constant = self.uiscreen.height * 0.12
//            barcodeImageHeight.constant = 83

        } else {
            barcodeImageHeight.constant = 0
        }
        
        let couponsValueString = String(marketPassDetails?._total_available_discount ?? 0.0)
        let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Regular", size: 17) ?? UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]
        let attrBold = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-Bold", size: 17) ?? UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]
        
        let couponsValueNormalText1 = "Έχεις κουπόνια συνολικής αξίας "
        let couponsValueBoldText  = couponsValueString + "€"

        let couponsValueAttributedString = NSMutableAttributedString(string:couponsValueNormalText1, attributes:attrRegular)
        let couponsValueBoldString = NSMutableAttributedString(string: couponsValueBoldText, attributes:attrBold)

        couponsValueAttributedString.append(couponsValueBoldString)
        couponsValueLabel.attributedText = couponsValueAttributedString
        
        let supermarkets: Array<swiftApi.SupermarketModel> = marketPassDetails?._supermarkets ?? []
        
        // Create a horizontal stack view
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 15 // Spacing between images
        stackView.alignment = .center
        stackView.distribution = .equalSpacing
        
        // Load images dynamically
        for sm in supermarkets {
            let imageView = UIImageView()
            imageView.contentMode = .scaleAspectFit
            imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
            imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
            
            imageView.load(link: sm._logo, placeholder: UIImage(), cache: URLCache())
            
            // Add image view to the stack view
            stackView.addArrangedSubview(imageView)
        }
        
        // Add the stack view to your main view
        smLogosView.addSubview(stackView)
        
        // Set up constraints for the stack view
        stackView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            stackView.leadingAnchor.constraint(equalTo: smLogosView.leadingAnchor, constant: 25),
            stackView.centerYAnchor.constraint(equalTo: smLogosView.centerYAnchor),
        ])

        passContainerView.isHidden = false
        self.view.layoutIfNeeded()
    }

    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 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 constructBarcode() -> String? {
        // EAN 13 barcode construction
        //TODO: FIX
//        let couponString = coupon?._barcode ?? ""
        let couponString = "123456789101112"
        
        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: - API Functions
    func getMarketPassDetailsRequest() {
        showSpinner()

        swiftApi().getMarketPassDetailsAsync(getMarketPassDetailsCallback, failureCallback: {errorCode in
            print("========= getMarketPassDetailsRequest ERROR CODE =========", errorCode)
            self.hideSpinner()
            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        })
    }

    func getMarketPassDetailsCallback (_ marketPassDetailsData: swiftApi.MarketPassDetailsModel?) -> Void {
        self.hideSpinner()

        if (marketPassDetailsData != nil) {
            DispatchQueue.main.async {
                if let tempMarketPassDetailsData = marketPassDetailsData {
                    self.marketPassDetails = tempMarketPassDetailsData
                    self.updateUI()
                }
            }
        } else {
            self.showDialog("Αποτυχία","Κάτι πήγε στραβά")
        }
    }
    // MARK: - API Functions
    
    // MARK: - Actions
    @IBAction func mapButtonAction(_ sender: Any) {
        swiftApi().openSupermarketMap(self)
    }
    
}