UnifiedCouponBarcodeViewController.swift 28.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
//
//  UnifiedCouponBarcodeViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 6/4/23.
//

import UIKit
import RSBarcodes_Swift
import AVFoundation
// import SwiftEventBus

final class ContentSizedTableView: UITableView {
    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize:CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}

//extension UIScrollView {
//    func updateContentView() {
//        contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
//    }
//}

extension UITableView {
    func updateContentView() {
        contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
    }
}

@objc public class UnifiedCouponBarcodeViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var mainView: UIView!
    @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 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 termsButton: UIButton!
    @IBOutlet weak var termsTextView: UnselectableTappableTextView!
    @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!
    @IBOutlet weak var topBorderLine: UIImageView!
    @IBOutlet weak var mapButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var mapButtonTopSpace: NSLayoutConstraint!
    @IBOutlet weak var showBarcodeButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var showBarcodeButtonTopSpace: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var showCouponsButton: UIButton!
    
    let uiscreen: CGRect = UIScreen.main.bounds
    
    var termsVisible: Bool = false;
    var barcodeVisible: Bool = false;
    var couponsVisible: Bool = false;

    var mapBtnVisible: Bool = false;
    var eshopBtnVisible: Bool = false;
    var eshopWebsite: String = "";
    
    public var coupon: swiftApi.UnifiedCouponModel?
    public var isFromWallet: Bool? = false
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hidesBottomBarWhenPushed = true
        merchantDescrTextView.delegate = self
        termsTextView.delegate = self
        
        tableView.delegate = self
        tableView.dataSource = self

        // Do any additional setup after loading the view.
        setBackButton()
        setNavigationTitle("Εκπτωτικό κουπόνι")

        // backgroundImage.image = UIImage(named: "coupons_scrollview_white", in: Bundle(for: MyEmptyClass.self), compatibleWith: nil)
        backgroundImage.image = UIImage(named: "coupons_scrollview_white", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)
        
//        scrollView.clipsToBounds = true
//        scrollView.layer.cornerRadius = 30
//        scrollView.layer.maskedCorners = [ .layerMinXMinYCorner] // Top left corner radius
        
        let image = UIImage(named: "top_border_line", in: MyEmptyClass.resourceBundle(), compatibleWith: nil)!
        var aspectR: CGFloat = 0.0

        aspectR = image.size.width/image.size.height

        topBorderLine.translatesAutoresizingMaskIntoConstraints = false
        topBorderLine.image = image
        topBorderLine.contentMode = .scaleAspectFill

        NSLayoutConstraint.activate([
            topBorderLine.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 0),
            topBorderLine.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 0),
            topBorderLine.trailingAnchor.constraint(equalTo: mainView.trailingAnchor, constant: 0),
            topBorderLine.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width),
            topBorderLine.heightAnchor.constraint(equalTo: topBorderLine.widthAnchor, multiplier: 1/aspectR)
        ])
        
        //        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 = 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;
//            }
//        }
        
        couponView.layer.cornerRadius = 8
        couponNumberLabel.text = ((coupon?._code != 0) ? String(coupon?._code ?? 0) : "")
        couponView.frame = CGRect(x: 0.0, y: 0.0, width: couponView.intrinsicContentSize.width, height: 55)
        
        let barcodeString = constructBarcode() ?? ""
        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
        }
        
        // === 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
        // ===
        
        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_2.png", in: MyEmptyClass.resourceBundle(), 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);
        showBarcodeButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        
        if let earliestExpiration = coupon?._coupons.min(by: { ($0.expiration ?? "") < ($1.expiration ?? "") }) {
            expirationLabel.text = "Το κουπόνι ισχύει έως " + (earliestExpiration.expiration ?? "")
        } else {
            expirationLabel.text = ""
        }

        mapButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Medium", size: 18)
        mapButton.setTitle("Δες τα supermarket", for: .normal)
        mapButton.setTitleColor(UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00), for: .normal)
        mapButton.backgroundColor = UIColor(red: 0.47, green: 0.75, blue: 0.08, alpha: 1.00)
        mapButton.layer.cornerRadius = 8.0
        mapButton.frame = CGRect(x: 0.0, y: 0.0, width: mapButton.intrinsicContentSize.width, height: 44)
        mapButton.contentEdgeInsets = UIEdgeInsets(top: 1, left: 16, bottom: 0, right: 16)

        // mapButton.isHidden = true
        // mapButtonHeight.constant = 0
        // mapButtonTopSpace.constant = 0
        
        // let merchantList:Array<swiftApi.MerchantModel> = swiftApi().getMerchantList()
        
        // for merchant in merchantList {
        //     if (merchant._uuid == couponSetData?.merchant_uuid) {
        //         if (merchant._show_map == true) {
        //             mapButton.setTitle("Δες τα καταστήματα", for: .normal)
        //             mapButton.frame = CGRect(x: 0.0, y: 0.0, width: mapButton.intrinsicContentSize.width, height: 44)
        //             mapButton.contentEdgeInsets = UIEdgeInsets(top: 1, left: 16, bottom: 0, right: 16)
        //             mapButton.isHidden = false
        //             mapBtnVisible = true
        //             eshopBtnVisible = false
        //             mapButtonHeight.constant = 44
        //             mapButtonTopSpace.constant = 10
        //         } else if (merchant._eshop == true) {
        //             mapButton.setTitle("Δες το eshop", for: .normal)
        //             mapButton.frame = CGRect(x: 0.0, y: 0.0, width: mapButton.intrinsicContentSize.width, height: 44)
        //             mapButton.contentEdgeInsets = UIEdgeInsets(top: 1, left: 16, bottom: 0, right: 16)
        //             mapButton.isHidden = false
        //             mapBtnVisible = false
        //             eshopBtnVisible = true
        //             mapButtonHeight.constant = 44
        //             mapButtonTopSpace.constant = 10
        //         } else {
        //             mapButton.isHidden = true
        //             mapBtnVisible = false
        //             eshopBtnVisible = false
        //             mapButtonHeight.constant = 0
        //             mapButtonTopSpace.constant = 0
        //         }
        //         eshopWebsite = merchant._website
        //         break;
        //     }
        // }

        // Fix width for ipad
//        if UIDevice.current.userInterfaceIdiom == .pad {
//             // iPad
//            mapButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
//         } else {
//             // not iPad (iPhone, mac, tv, carPlay, unspecified)
//             mapButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.6).isActive = true
//         }
        
        showCouponsButton.titleLabel?.font = UIFont(name: "PFSquareSansPro-Regular", size: 16)
//        termsButton.imageView?.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
        showCouponsButton.setTitle("Εμφάνιση κουπονιών", for: .normal)
        showCouponsButton.setTitleColor(UIColor(red: 0.25, green: 0.33, blue: 0.39, 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.21, green: 0.32, blue: 0.41, alpha: 1.00)
        showCouponsButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0);
        showCouponsButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5);
        showCouponsButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        
//        tableView.isScrollEnabled = false
//        tableView.isHidden = true
//        tableViewHeight.constant = CGFloat(0)
        
//        tableView.isHidden = false
//        let targetSize = CGSize(width: tableView.frame.width, height: CGFloat(MAXFLOAT))
//        tableViewHeight.constant = tableView.sizeThatFits(targetSize).height

        
        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_2.png", in: MyEmptyClass.resourceBundle(), 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);
        termsButton.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
        
        let termsText = "1. Το εκπτωτικό κουπόνι ισχύει έως την ημερομηνία που αναφέρεται παραπάνω\n2. To εκπτωτικό κουπόνι αφορά στα ενεργά κουπόνια προσφορών όπως αναφέρονται παραπάνω.\n3. Το εκπτωτικό κουπόνι μπορεί να χρησιμοποιηθεί σε μια μόνο συναλλαγή.\n4. Εάν δεν γίνει χρήση ενός επιμέρους κουπονιού προσφοράς από το εκπτωτικό κουπόνι, το κουπόνι προσφοράς επιστρέφει στο καλάθι στην ενότητα COSMOTE SuperMarket Deals"
        termsTextView.attributedText = NSAttributedString(string: termsText)
        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
        
        termsTextView.isUserInteractionEnabled = true
        termsTextView.isEditable = false
        termsTextView.isSelectable = true
        termsTextView.dataDetectorTypes = [.link]
        
        // Uncomment if Barcode Section is active again
//        toggleTerms()
//        toggleBarcode()

        // Logs
//        print("Coupon: " + (coupon?.coupon ?? ""))
//        print("Coupon Name: " + (couponSetData?.name ?? ""))
//        print("Coupon Description: " + (couponSetData?.short_description ?? ""))
//        print("Coupon Expiration: " + (coupon?.expiration ?? ""))
        
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        swiftApi().logTrackersEvent("screen", "UnifiedCouponScreen")
        
    }
    
    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
    }

    
    // 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_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        } else {
            termsTextView.isHidden = true
            termsTextViewHeight.constant = CGFloat(0)
            
            termsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), 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_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() {
        if (couponsVisible) {
            tableView.isHidden = false
            let targetSize = CGSize(width: tableView.frame.width, height: CGFloat(MAXFLOAT))
            tableViewHeight.constant = tableView.sizeThatFits(targetSize).height
            
//            tableViewHeight.constant = tableView.intrinsicContentSize.height
            
            showCouponsButton.setImage(UIImage(named: "ic_up_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        } else {
            tableView.isHidden = true
            tableViewHeight.constant = CGFloat(0)
            
            showCouponsButton.setImage(UIImage(named: "ic_down_dark_2.png", in: MyEmptyClass.resourceBundle(), compatibleWith: nil), for: .normal)
        }
//        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.intrinsicContentSize.height);
//        self.view.layoutIfNeeded()
//        let targetSize = CGSize(width: scrollView.frame.width, height: CGFloat(MAXFLOAT))
//        tableViewHeight.constant = tableView.sizeThatFits(targetSize).height
        
//        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, CGFloat(MAXFLOAT));
//        scrollView.updateContentView()
//        tableView.updateContentView()
    }
    
    func constructBarcode() -> 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 ""
    }
    
    // MARK: - Actions
    @IBAction func showCouponsButtonAction(_ sender: Any) {
        couponsVisible = !couponsVisible
//        self.tableView.reloadSections(IndexSet(0..<2), with: .none)
        self.tableView.reloadData()
//        toggleCoupons()
    }
    
    @IBAction func showBarcodeAction(_ sender: Any) {
        barcodeVisible = !barcodeVisible
//        self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
        self.tableView.reloadData()
//        toggleBarcode()
    }
    
    @IBAction func termsButtonAction(_ sender: Any) {
        termsVisible = !termsVisible
//        self.tableView.reloadSections(IndexSet(integer: 2), with: .none)
        self.tableView.reloadData()
//        toggleTerms()
    }

    @IBAction func mapButtonAction(_ sender: Any) {
        swiftApi().logTrackersEvent("click", "SeeShops")
//
        let vc = SwiftWarplyFramework.MapsViewController(nibName: "MapsViewController", bundle: Bundle(for: MyEmptyClass.self))
//        vc.couponSet = coupon?.couponset_data
        self.navigationController?.pushViewController(vc, animated: true)

        // if (mapBtnVisible == true) {
        //     swiftApi().logTrackersEvent("click", "SeeShops")
            
        //     let vc = SwiftWarplyFramework.MapsViewController(nibName: "MapsViewController", bundle: Bundle(for: MyEmptyClass.self))
        //     vc.couponSet = coupon?.couponset_data
        //     self.navigationController?.pushViewController(vc, animated: true)

        // } else if (eshopBtnVisible == true) {
        //     if (eshopWebsite != "") {
        //         guard let websiteUrl = URL(string: eshopWebsite) else {
        //               print("Error creating URL")
        //               return
        //         }
                
        //         // check if link can be opened.
        //         guard UIApplication.shared.canOpenURL(websiteUrl) else {
        //             return
        //         }
                
        //         swiftApi().logTrackersEvent("click", "SeeShopWebsite")
        //         UIApplication.shared.open(websiteUrl, options: [:], completionHandler: nil)
        //     }
        // }
    }
}

// MARK: - TableView
extension UnifiedCouponBarcodeViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0) {
            return 1
        } else if (section == 1) {
            if (couponsVisible == true) {
                return self.coupon?._coupons.count ?? 0
            } else {
                return 0
            }
            
        } else if (section == 2) {
            return 1
        } else {
            return 0
        }

    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath.section == 0) {
            return UITableView.automaticDimension
        } else if (indexPath.section == 1) {
            if (couponsVisible == true) {
                return 120.0 + 8.0
            } else {
                return 0.0
            }
            
        } else if (indexPath.section == 2) {
            return UITableView.automaticDimension
        } else {
            return 0.0
        }
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UnifiedCouponBCHeaderTableViewCell", for: indexPath) as! UnifiedCouponBCHeaderTableViewCell
            
            cell.configureCell(coupon: self.coupon, couponsVisible: couponsVisible)
            
            return cell
            
        } else if (indexPath.section == 1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CouponsTableViewCellId", for: indexPath) as! CouponsTableViewCell
            
            cell.configureCell(coupon: (self.coupon?._coupons[indexPath.row])!, isMarket: true)
            
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UnifiedCouponBCFooterTableViewCell", for: indexPath) as! UnifiedCouponBCFooterTableViewCell
            
            cell.configureCell(termsVisible: termsVisible)
            
            return cell
        }
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // SwiftEventBus.post("couponBarcodePressed", sender: coupons[indexPath.row])
        
        // Logs
//        let couponSetData: swiftApi.CouponSetItemModel? = coupons[indexPath.row].couponset_data
//        print("Coupon clicked: " + (coupons[indexPath.row].coupon ?? ""))
//        print("Coupon Name clicked: " + (couponSetData?.name ?? ""))
//        print("Coupon Description clicked: " + (couponSetData?.short_description ?? ""))
//        print("Coupon Expiration clicked: " + (coupons[indexPath.row].expiration ?? ""))
        
//        swiftApi().logTrackersEvent("click", ("Coupon:" + (couponSetData?.name ?? "")))

//        let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
//        let vc = storyboard.instantiateViewController(withIdentifier: "CouponBarcodeViewController") as! SwiftWarplyFramework.CouponBarcodeViewController
//        vc.coupon = self.coupon?._coupons[indexPath.row]
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}