CouponsTableViewCell.swift 17.7 KB
//
//  CouponsTableViewCell.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 18/5/22.
//

import Foundation
import UIKit

@objc public class CouponsTableViewCell: UITableViewCell {
    @IBOutlet weak var couponBgImage: UIImageView!
    @IBOutlet weak var couponImage: UIImageView!
    @IBOutlet weak var borderView: UIView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var dicountLabel: UILabel!
    @IBOutlet weak var discriptionLabel: UILabel!
    @IBOutlet weak var expirationLabel: UILabel!
    @IBOutlet weak var expirationRedView: UIView!
    @IBOutlet weak var expirationRedImage: UIImageView!
    @IBOutlet weak var expirationRedLabel: UILabel!
    
    let smCouponsetsList = swiftApi().getCouponSetsDealsList()
    
    // Variables for the view, image, and button
    var selectView: UIView!
    var selectImageView: UIImageView!
    var selectButton: UIButton!
    
    // Boolean to track if the selectView should be visible
    var isSelectViewVisible: Bool = false {
        didSet {
            selectView.isHidden = !isSelectViewVisible
        }
    }

    // Boolean to track the selection state of the cell
    var isSelectedCell: Bool = false {
        didSet {
            updateSelectionState()
        }
    }
    
    // Action closure for button tap inside the cell
    var selectButtonAction: (() -> Void)?

    var postImageURL: String? {
        didSet {
            if let url = postImageURL {
                self.couponImage.image = UIImage() // UIImage(named: "loading")

                UIImage.loadImageUsingCacheWithUrlString(url) { image in
                    // set the image only when we are still displaying the content for the image we finished downloading
                    if url == self.postImageURL {
                        self.couponImage.image = image
                    }
                }
            }
            else {
                self.couponImage.image = nil
            }
        }
    }
    
    
    public override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        couponBgImage.image = UIImage(named: "coupon_bg_2", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        
        borderView.addDashedBorderVertical(color: UIColor(red: 0.62, green: 0.62, blue: 0.61, alpha: 1.00), width: 1.0, height: 110.0)
        
        setupSelectButton()
    }

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

        // Configure the view for the selected state
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        //set the values for top,left,bottom,right margins
        let margins = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
        contentView.frame = contentView.frame.inset(by: margins)
    }
    
    // Setup Select Button UI and layout
    func setupSelectButton() {
        // Create the container view (selectView)
        selectView = UIView()
        selectView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(selectView)

        // Set selectView constraints
        NSLayoutConstraint.activate([
            selectView.widthAnchor.constraint(equalToConstant: 26),
            selectView.heightAnchor.constraint(equalToConstant: 26),
            selectView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6),
            selectView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16)
        ])
        
        // Create the UIImageView inside selectView
        selectImageView = UIImageView()
        selectImageView.contentMode = .scaleAspectFit
        selectImageView.translatesAutoresizingMaskIntoConstraints = false
        selectView.addSubview(selectImageView)
        
        // Set imageView constraints to match the size of the selectView
        NSLayoutConstraint.activate([
            selectImageView.leadingAnchor.constraint(equalTo: selectView.leadingAnchor),
            selectImageView.trailingAnchor.constraint(equalTo: selectView.trailingAnchor),
            selectImageView.topAnchor.constraint(equalTo: selectView.topAnchor),
            selectImageView.bottomAnchor.constraint(equalTo: selectView.bottomAnchor)
        ])
        
        // Create the transparent button on top of the imageView
        selectButton = UIButton(type: .custom)
        selectButton.backgroundColor = .clear // Make the button transparent
        selectButton.translatesAutoresizingMaskIntoConstraints = false
        selectButton.addTarget(self, action: #selector(selectButtonTapped), for: .touchUpInside)
        selectView.addSubview(selectButton)
        
        // Set button constraints to match the size of the selectView
        NSLayoutConstraint.activate([
            selectButton.leadingAnchor.constraint(equalTo: selectView.leadingAnchor),
            selectButton.trailingAnchor.constraint(equalTo: selectView.trailingAnchor),
            selectButton.topAnchor.constraint(equalTo: selectView.topAnchor),
            selectButton.bottomAnchor.constraint(equalTo: selectView.bottomAnchor)
        ])
        
        // Initially hide the selectView (selectView)
        selectView.isHidden = true
    }
    
    // Button action handler
    @objc func selectButtonTapped() {
        // Trigger the action closure when the button is pressed
        selectButtonAction?()
    }
    
    // Update the cell's appearance based on selection state
    func updateSelectionState() {
        // Update the image based on the new state
        if (isSelectedCell) {
            selectImageView.image = UIImage(named: "circle_checked", in: MyEmptyClass.resourceBundle(), compatibleWith: nil) // Selected image
        } else {
            selectImageView.image = UIImage(named: "circle_unchecked", in: MyEmptyClass.resourceBundle(), compatibleWith: nil) // Unselected image
        }
    }
    
    func configureCell(coupon: swiftApi.CouponItemModel) {
//        COUPONSET: desc, img_preview, name, terms, merchant_uuid, discount_type, final_price
//        COUPON: coupon, expiration, discount, status
//        MERCHANT: _img_preview,_admin_name
        
        // Add shadow
        self.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 1.0
        
        let merchantList:Array<swiftApi.MerchantModel> = swiftApi().getMerchantList()
        
        let couponSetData: swiftApi.CouponSetItemModel? = coupon.couponset_data
        
        nameLabel.text = ""
        
        // for merchant in merchantList {
        //     // if (merchant._uuid == couponSetData?.merchant_uuid) {
        //     if (merchant._uuid == coupon.merchant_uuid) {
        //         // couponImage.load(link: merchant._img_preview, placeholder: UIImage(), cache: URLCache())
        //         self.postImageURL = merchant._img_preview
        //         nameLabel.text = merchant._admin_name
        //         break;
        //     }
        // }

        let merchantDetails: swiftApi.MerchantModel? = coupon.merchant_details
        self.postImageURL = merchantDetails?._img_preview
        nameLabel.text = merchantDetails?._admin_name
        
//        couponImage.load(link: couponSetData?.img_preview ?? "", placeholder: UIImage(), cache: URLCache())
//        nameLabel.text = couponSetData?.name ?? ""
        let discount = couponSetData?.discount_type == "value" ? ((coupon.discount ?? "") + "€")
        : couponSetData?.discount_type == "percentage" ? ((coupon.discount ?? "") + "%")
        : couponSetData?.discount_type == "plus_one" ? "1+1"
        : ((coupon.discount ?? "") + "€")
        dicountLabel.text = discount
        // let htmlText = couponSetData?.inner_text ?? ""
        // discriptionLabel.text = htmlText.htmlToString
        discriptionLabel.text = couponSetData?.inner_text ?? ""
        expirationLabel.text = "Ισχύει έως "+(coupon.expiration ?? "")
    }
    
    func configureCell(coupon: swiftApi.CouponItemModel, isMarket: Bool) {
//        COUPONSET: desc, img_preview, name, terms, merchant_uuid
//        COUPON: coupon, expiration, discount, status
//        MERCHANT: _img_preview,_admin_name
        
        var couponSetData: swiftApi.CouponSetItemModel?
        for item in smCouponsetsList {
            if (item.uuid == coupon.couponset_uuid) {
                couponSetData = item
                break;
            }
        }
        
//        // Add shadow
        contentView.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        contentView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        contentView.layer.shadowOpacity = 1.0
        contentView.layer.shadowRadius = 1.0
        
        expirationLabel.isHidden = true
        expirationRedView.isHidden = true
        expirationLabel.text = ""
        expirationRedLabel.text = ""
        
        if (coupon.status == 1) { // Active status 1
            // Add shadow
//            self.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.16).cgColor
//            self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
//            self.layer.shadowOpacity = 1.0
//            self.layer.shadowRadius = 6.0
            
//            couponBgImage.image = UIImage(named: "coupon_bg", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
            
            couponImage.layer.opacity = 1
            borderView.layer.opacity = 1
            nameLabel.layer.opacity = 1
            dicountLabel.layer.opacity = 1
            discriptionLabel.layer.opacity = 1
            
            expirationLabel.isHidden = false
            expirationRedView.isHidden = true
            expirationLabel.text = "Ισχύει έως "+(coupon.expiration ?? "")
            
            let formatter = DateFormatter()
            formatter.dateFormat = "dd/MM/yyyy"
            let today = Date()
//            let firstDate = formatter.date(from: "01/08/2017")
//            let secondDate = formatter.date(from: "22/04/2023")
            if let couponExpiration = coupon.expiration, let secondDate = formatter.date(from: couponExpiration) {
                
                let calendar = NSCalendar.current
                let date1 = calendar.startOfDay(for: today)
                let date2 = calendar.startOfDay(for: secondDate)

                let differenceComponents = calendar.dateComponents([.day], from: date1, to: date2)
                
                if let daysDifference = differenceComponents.day {
                    if ((daysDifference >= 0) && (daysDifference <= 15)) {
                        
                        expirationLabel.isHidden = true
                        expirationRedView.isHidden = false
                        expirationRedView.layer.cornerRadius = 10.0
                        expirationRedView.backgroundColor = UIColor(red: 0.72, green: 0.88, blue: 0.94, alpha: 1.00)
                        
                        expirationRedImage.image = UIImage(named: "ic_time_forward_blue", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
                        
                        let normalText1 = "Ισχύει έως "
                        let redText  = (coupon.expiration ?? "")

                        let attrRegular = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-SBold", size: 12) ?? UIFont.systemFont(ofSize: 11), NSAttributedString.Key.foregroundColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1.00)]
                        let attrRed = [NSAttributedString.Key.font : UIFont(name: "PeridotPE-SBold", size: 12) ?? UIFont.systemFont(ofSize: 11), NSAttributedString.Key.foregroundColor: UIColor(red: 0.00, green: 0.29, blue: 0.53, alpha: 1.00)]

                        let attributedString = NSMutableAttributedString(string:normalText1, attributes:attrRegular)
                        let RedString = NSMutableAttributedString(string: redText, attributes:attrRed)

                        attributedString.append(RedString)
                        expirationRedLabel.attributedText = attributedString
                        
                    } else {
                        expirationLabel.isHidden = false
                        expirationRedView.isHidden = true
                        expirationLabel.text = "Ισχύει έως "+(coupon.expiration ?? "")
                    }
                }
            }
            
        } else if (coupon.status == 0) { // Redeemed status 0
//            couponBgImage.image = UIImage(named: "coupon_bg_grey", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
            
            expirationLabel.isHidden = false
            expirationRedView.isHidden = true
            expirationLabel.text = "Το κουπόνι έληξε"
            
            couponImage.layer.opacity = 0.29
            borderView.layer.opacity = 0.29
            nameLabel.layer.opacity = 0.29
            dicountLabel.layer.opacity = 0.29
            discriptionLabel.layer.opacity = 0.29
            
        } else { // Expired status -1
            
            expirationLabel.isHidden = false
            expirationRedView.isHidden = true
            expirationLabel.text = "Το κουπόνι έληξε"
            
            couponImage.layer.opacity = 0.29
            borderView.layer.opacity = 0.29
            nameLabel.layer.opacity = 0.29
            dicountLabel.layer.opacity = 0.29
            discriptionLabel.layer.opacity = 0.29
            
        }
                
        let merchantList:Array<swiftApi.MerchantModel> = swiftApi().getMerchantList()

        nameLabel.text = ""
        
        for merchant in merchantList {
            if (merchant._uuid == coupon.merchant_uuid) {
                // couponImage.load(link: merchant._img_preview, placeholder: UIImage(), cache: URLCache())
//                self.postImageURL = merchant._img_preview
                nameLabel.text = merchant._admin_name
                break;
            }
        }
        
        self.postImageURL = couponSetData?.img_preview
        
//        let priceFloat = Float(round(100 * (Float(coupon.discount ?? "0.0") ?? 0.0 )) / 100)
//        var priceString = "0"
//        priceString  = String(format: "%.2f", priceFloat).replacingOccurrences(of: ".", with: ",", options: .literal, range: nil)
//        dicountLabel.text = priceString + "€"
        
        dicountLabel.text = (coupon.discount ?? "").replacingOccurrences(of: ".", with: ",", options: .literal, range: nil) + "€"
        
        let htmlText = coupon.inner_text ?? ""
        discriptionLabel.text = htmlText.htmlToString
//        discriptionLabel.text = coupon.inner_text ?? ""
        
     }
    
    func configureCell(coupon: swiftApi.CouponItemModel, isSMCoupon: Bool) {
//        COUPONSET: desc, img_preview, name, terms, merchant_uuid, discount_type, final_price
//        COUPON: coupon, expiration, discount, status
//        MERCHANT: _img_preview,_admin_name
        
        // Add shadow
        self.layer.shadowColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.2).cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 1.0
        
        let merchantList:Array<swiftApi.MerchantModel> = swiftApi().getMerchantList()
        
        let couponSetData: swiftApi.CouponSetItemModel? = coupon.couponset_data
        
        nameLabel.text = ""
        
        // for merchant in merchantList {
        //     // if (merchant._uuid == couponSetData?.merchant_uuid) {
        //     if (merchant._uuid == coupon.merchant_uuid) {
        //         // couponImage.load(link: merchant._img_preview, placeholder: UIImage(), cache: URLCache())
        //         self.postImageURL = merchant._img_preview
        //         nameLabel.text = merchant._admin_name
        //         break;
        //     }
        // }
        
        let merchantDetails: swiftApi.MerchantModel? = coupon.merchant_details
        self.postImageURL = couponSetData?.img_preview
        nameLabel.text = merchantDetails?._admin_name
        
//        couponImage.load(link: couponSetData?.img_preview ?? "", placeholder: UIImage(), cache: URLCache())
//        nameLabel.text = couponSetData?.name ?? ""
        let discount = couponSetData?.discount_type == "value" ? ((coupon.discount ?? "") + "€")
        : couponSetData?.discount_type == "percentage" ? ((coupon.discount ?? "") + "%")
        : couponSetData?.discount_type == "plus_one" ? "1+1"
        : ((coupon.discount ?? "") + "€")
        dicountLabel.text = discount
        // let htmlText = couponSetData?.inner_text ?? ""
        // discriptionLabel.text = htmlText.htmlToString
        discriptionLabel.text = couponSetData?.inner_text ?? ""
        expirationLabel.text = "Ισχύει έως "+(coupon.expiration ?? "")
    }
    
    // Configure the cell with visibility of the selectView, a selected state, and select Button Action
    func showSelectButton(isSelectViewVisible: Bool, isSelected: Bool, buttonAction: @escaping () -> Void) {
        self.isSelectViewVisible = isSelectViewVisible
        self.isSelectedCell = isSelected
        self.selectButtonAction = buttonAction
        
        if (isSelected) {
            couponBgImage.image = UIImage(named: "coupon_bg_2_selected", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        } else {
            couponBgImage.image = UIImage(named: "coupon_bg_2", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        }
        
        // Set nameLabel constraints to not overlap selectView
        NSLayoutConstraint.activate([
            nameLabel.trailingAnchor.constraint(equalTo: selectView.leadingAnchor, constant: -5)
        ])
        
    }
}