//
//  GDPRSettingsViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 25.06.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.
//

import UIKit

class GDPRSettingsViewController: UIViewController {

    @IBOutlet private var infoView: AdBlockView!

    private let consentURL = "https://demofiles.smaato.com/cmp/index.html"
    private lazy var gdprAPI: CMPConsentToolAPI = {
        let api = CMPConsentToolAPI()
        api.subjectToGDPR = .unknown
        api.cmpPresent = true
        return api
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        showGDPRInfo(fromTool: gdprAPI)
    }

    //MARK: Actions

    @IBAction private func showGDPRTool(_: Any?) {
        let toolVC = CMPConsentToolViewController()
        toolVC.consentToolURL = URL(string: consentURL)
        toolVC.consentToolAPI = gdprAPI
        toolVC.delegate = self
        self.present(toolVC, animated: true, completion: nil)
    }

    //MARK: Private

    private func showGDPRInfo(fromTool gdprTool: CMPConsentToolAPI) {
        var str = String()

        str += "SubjectToGDPR: \(gdprTool.subjectToGDPR.rawValue)\n\n"
        str += "ConsentString: \(String(describing: gdprTool.consentString))\n\n"
        str += "VendorConsentBitString: \(String(describing: gdprTool.parsedVendorConsents))\n\n"
        str += "PurposeConsentBitString: \(String(describing: gdprTool.parsedPurposeConsents))\n\n"
        str += "CmpPresent: \(gdprTool.cmpPresent)\n\n"

        let vendorId: Int32 = 82
        let vendorConsent = gdprTool.isVendorConsentGiven(for: vendorId)
        let consentString = vendorConsent ? "YES" : "NO"
        str += "Consent for vendor ID: \(vendorId) = \(consentString)\n\n"

        for purposeId: Int32 in 1...5 {
            let purposeConsent = gdprTool.isPurposeConsentGiven(for: purposeId)
            let purposeString = purposeConsent ? "YES" : "NO"
            str += "Consent for purpose ID: \(purposeId) = \(purposeString)\n"
        }

        infoView.tip = str
        infoView.tipAlignment = .left
    }

}

extension GDPRSettingsViewController: CMPConsentToolViewControllerDelegate {

    func consentToolViewController(_ consentToolViewController: CMPConsentToolViewController!, didReceiveConsentString consentString: String!) {
        showGDPRInfo(fromTool: consentToolViewController.consentToolAPI)
        self.dismiss(animated: true, completion: nil)
    }

}
