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

import Foundation
import ConsentViewController

class GDPRHelperV2: GDPRHelper {
    
    weak var parentVC: UIViewController?

    weak var delegate: GDPRHelperDelegate?
    
    init(withParentViewController viewController: UIViewController) {
        self.parentVC = viewController
    }
    
    public var infoString: String {
        var str = String()
        
        str = str.appendingFormat("Purpose One Consent : \(purposeOneConsentGiven ? "True" : "False")\n\n")
        str = str.appendingFormat("Purpose Two Consent : \(purposeTwoConsentGiven ? "True" : "False")\n\n")
        str = str.appendingFormat("Purpose Two LI : \(purposeTwoLIGiven ? "True" : "False")\n\n")
        str = str.appendingFormat("Vendor Consent : \(isSmaatoAuthorized ? "True" : "False")\n\n")
        str = str.appendingFormat("Vendor LI : \(vendorLIGiven ? "True" : "False")\n\n")
        str = str.appendingFormat("Special Feature One Consent : \(specialPurposeOneConsent ? "True" : "False")\n\n")
        str = str.appendingFormat("GDPR Applies : \(subjectToGDPR.rawValue)\n\n")

        return str
    }
    
    var shouldShowConsentDialogMessage: Bool {
        if ((subjectToGDPR == .yes || subjectToGDPR == .unknown) && (consentString ?? "").isEmpty) {
            return true;
        }
        
        return false;
    }
    
    private lazy var consentViewController: GDPRConsentViewController = {
        return GDPRConsentViewController(
            accountId: 1081,
            propertyId: 4992,
            propertyName: try! GDPRPropertyName("demo.smaato.ios"),
            PMId: "118788",
            campaignEnv: .Public,
            consentDelegate: self
    )}()
    
    func showConsentDialog() {
        consentViewController.loadPrivacyManager()
    }
    
    func deleteConsentInformation() {
        consentViewController.clearAllData()
        delegate?.needsUpdateGDPRInformation()
    }
}

extension GDPRHelperV2 {
    
    private var consentString: String? {
        if let consentString = UserDefaults.standard.value(forKey: "IABTCF_TCString") as? String {
            return consentString
        }
        return nil
    }
    
    private var isSmaatoAuthorized: Bool {
        return decodeConsent(atPosition: 82, withKey: "SMA_IABTCF_VendorConsents")
    }

    private var purposeOneConsentGiven: Bool {
        return decodeConsent(atPosition: 1, withKey: "SMA_IABTCF_PurposeConsents")
    }
    
    private var purposeTwoConsentGiven: Bool {
        return decodeConsent(atPosition: 2, withKey: "SMA_IABTCF_PurposeConsents")
    }
    
    private var purposeTwoLIGiven: Bool {
        return decodeConsent(atPosition: 2, withKey: "SMA_IABTCF_PurposeLegitimateInterests")
    }

    private var vendorLIGiven: Bool {
        return decodeConsent(atPosition: 82, withKey: "SMA_IABTCF_VendorLegitimateInterests")
    }

    private var specialPurposeOneConsent: Bool {
        return decodeConsent(atPosition: 1, withKey: "SMA_IABTCF_SpecialFeaturesOptIns")
    }

    private func decodeConsent(atPosition position:Int, withKey key: String) -> Bool {
        let pos = position - 1
        var flag = false
         if let purposeConsents = UserDefaults.standard.value(forKey: key) as? String, purposeConsents.count > pos {
            let start = purposeConsents.index(purposeConsents.startIndex, offsetBy: pos)
            let end = purposeConsents.index(purposeConsents.startIndex, offsetBy: pos)
             flag = purposeConsents[start...end] == "1"
         }
        return flag
    }
        
    private var subjectToGDPR: SubjectToGDPR {
        if let gdprValue = UserDefaults.standard.value(forKey: "IABTCF_gdprApplies") as? NSInteger {
            if gdprValue == 0 {
                return .no
            } else if gdprValue == 1 {
                return .yes
            } else {
                return .unknown
            }
        }
        return .unknown
    }
}

extension GDPRHelperV2: GDPRConsentDelegate {
    func consentUIWillShow() {
        consentViewController.modalPresentationStyle = .fullScreen
        self.parentVC?.present(consentViewController, animated: true, completion: nil)
    }
    
    func consentUIDidDisappear() {
        delegate?.needsUpdateGDPRInformation()
    }
    
    func onConsentReady(gdprUUID: GDPRUUID, userConsent: GDPRUserConsent) {
        delegate?.needsUpdateGDPRInformation()
    }
    
    func onErrorOccurred(error: GDPRConsentViewControllerError) {
        print("Error: \(error.debugDescription)")
    }
}
