//
//  GDPRHelperV1.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 15.04.20.
//  Copyright © 2020 Smaato Inc. All rights reserved.
//

import Foundation

class GDPRHelperV1: NSObject, GDPRHelper {
    
    weak var parentVC: UIViewController?

    weak var delegate: GDPRHelperDelegate?
    
    init(withParentViewController viewController: UIViewController) {
        self.parentVC = viewController
    }

    var infoString: String {
        var str = String()
        
        let vendorId: Int32 = 82
        let vendorConsent = gdprAPIV1.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 = gdprAPIV1.isPurposeConsentGiven(for: purposeId)
            let purposeString = purposeConsent ? "YES" : "NO"
            str += "Consent for purpose ID: \(purposeId) = \(purposeString)\n\n"
        }

        str += "SubjectToGDPR: \(gdprAPIV1.subjectToGDPR.rawValue)\n\n"

        return str
    }
    
    var shouldShowConsentDialogMessage: Bool {
        let subject = gdprAPIV1.subjectToGDPR;
        if ((subject == .yes || subject == .unknown) && (gdprAPIV1.consentString ?? "").isEmpty) {
            return true;
        }
        
        return false;
    }

    private lazy var gdprAPIV1: CMPConsentToolAPI = {
        let api = CMPConsentToolAPI()
        api.subjectToGDPR = .unknown
        api.cmpPresent = true
        return api
    }()
    
    func showConsentDialog() {
        let consentToolVC = CMPConsentToolViewController()
        consentToolVC.consentToolURL = URL(string: "https://demofiles.smaato.com/cmp/index.html")
        consentToolVC.consentToolAPI = gdprAPIV1
        consentToolVC.delegate = self
        consentToolVC.modalPresentationStyle = .fullScreen;
        parentVC?.present(consentToolVC, animated: true, completion: nil)
    }
    
    func deleteConsentInformation() {
        gdprAPIV1.dataStorage.clearData()
        delegate?.needsUpdateGDPRInformation()
    }
}

extension GDPRHelperV1: CMPConsentToolViewControllerDelegate {
    func consentToolViewController(_ consentToolViewController: CMPConsentToolViewController!, didReceiveConsentString consentString: String!) {
        delegate?.needsUpdateGDPRInformation()
    }
}
