SubscriptionViewController.swift 5.54 KB
//
//  SubscriptionViewController.swift
//  browser
//
//  Created by Artem Talko on 24.11.2023.
//

import UIKit
import StoreKit

final class SubscriptionViewController: UIViewController {
    
    let mainView = SubscriptionView()
    
    private let tableViewData: [String]
    private let storeKitManager: SubscriptionManager
    private let successCompletion: () -> Void
    
    private var subscriptionInfo: SKProduct? {
            didSet {
                updateSubscriptionLabels()
            }
        }
    
    init(storeKit: SubscriptionManager, completion: @escaping() -> Void) {
        tableViewData = StringConstants.removeAdvertTableViewData
        storeKitManager = storeKit
        successCompletion = completion
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initViewController()
        updateSubscriptionLabels()
    }
    
    override func loadView() {
        view = mainView
    }
   
    private func initViewController() {
        addTargets()
        setupTableView()
        
        mainView.privacyButton.addTarget(self, action: #selector(policyTapped), for: .touchUpInside)
        mainView.termsButton.addTarget(self, action: #selector(termsTapped), for: .touchUpInside)
        mainView.restoreButton.addTarget(self, action: #selector(restoreTapped), for: .touchUpInside)
    }
    
    private func updateSubscriptionLabels() {
        mainView.priceLabel.text = storeKitManager.storeProducts.first?.displayPrice
       }
    
    private func presentViewController(_ viewController: UIViewController) {
        viewController.modalPresentationStyle = .fullScreen
        
        present(viewController, animated: true)
    }
}

//MARK: - Table View
extension SubscriptionViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableViewData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: SubscriptionTableViewCell.cellID) as?
                SubscriptionTableViewCell else {
            return UITableViewCell()
        }
        cell.advantagesCellLabel.text = tableViewData[indexPath.row]
        
        return cell
    }
}

//MARK: Helpers
extension SubscriptionViewController {
    private func addTargets() {
        mainView.closeButton.addTarget(self, action: #selector(closeViewController(_ :)), for: .touchUpInside)
        mainView.subscribeButton.addTarget(self, action: #selector(buyAdblocker), for: .touchUpInside)
    }
    
    private func setupTableView() {
        mainView.advantagesTableView.dataSource = self
        mainView.advantagesTableView.delegate = self
        mainView.advantagesTableView.register(SubscriptionTableViewCell.self, forCellReuseIdentifier: SubscriptionTableViewCell.cellID)
    }
    
    private func isSubscriptionValid() -> Bool {
        guard let expirationDate = CachingManager.shared.expirationDate else {
            return false
        }

        let currentDate = Date().timeIntervalSince1970
        return expirationDate > currentDate
    }
    
    @MainActor
    private func buySubscription() async throws {
        if CachingManager.shared.isSubscriptionActive {
            dismiss(animated: true)
            successCompletion()
            return
        }

        if let adblockerProduct = storeKitManager.storeProducts.first(where: { $0.id == SubscriptionsModel.subscriptionInfo["adBlocker"]}) {
            do {
                if let transaction = try await storeKitManager.purchase(adblockerProduct) {
                    CachingManager.shared.expirationDate = transaction.expirationDate?.timeIntervalSince1970 ?? 0
                    dismiss(animated: true)
                    successCompletion()

                    VPNAnalytics.logEvent(eventType: .startTrial, params: ["subscription_id": "\(transaction.originalID)"])
                }
            } catch {
                print("Error purchasing product: \(error)")
            }
        }

    }
}


//MARK: Action
extension SubscriptionViewController {
    @objc
    private func closeViewController(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    @objc
    private func buyAdblocker(_ sender: UIButton) {
        ProgressHelper.show()
        sender.isEnabled = false
    
        Task {
            defer {
                ProgressHelper.hide()
                
                sender.isEnabled = true
            }

            do {
                try await buySubscription()
            } catch {
                let alert = UIAlertController(title: "Fail!", message: "Error with subscription", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "OK", style: .default)
                alert.addAction(okAction)
                present(alert, animated: true)
            }
        }
    }


    
    @objc
    private func termsTapped() {
        let termsViewController = TermsViewController()
        presentViewController(termsViewController)
    }
    
    @objc
    private func policyTapped() {
        let privacyViewController = PrivacyViewController()
        presentViewController(privacyViewController)
    }
    
    @objc
    private func restoreTapped() {
        Task {
            try? await SubscriptionManager.shared.restorePurchase()
        }
    }
}