import { Component, OnInit, Injectable, Inject, ApplicationRef, PLATFORM_ID } from '@angular/core'
import { cookiebotId } from '@k-settings/app-setup'
import { Location, isPlatformBrowser } from '@angular/common'
import { Subject }                     from 'rxjs/Subject'
// Declares and adds dataLayer to the global scope


declare global {
    interface Window {
        Cookiebot: any;
    }
}

declare var CookiebotCallback_OnAccept


@Injectable()
export class CookieBotService {

    cookieBotSource = new Subject<any>()
    cookieBot$ = this.cookieBotSource.asObservable()

    cookieBotInterval: any
    values: any = {}

    constructor(
        @Inject(PLATFORM_ID) private platformId: Object,
        private appRef: ApplicationRef
    ) {


        // Changed from (!!window) to typeof check as webpack give error while building

        if(isPlatformBrowser(this.platformId) && !!cookiebotId && cookiebotId.length > 0) {

            // CookiebotCallback_OnAccept = () => {

            //     if(window.Cookiebot.consented) {

            //         console.log('consented')
            //         console.log(window.Cookiebot.consent)

            //         this.cookieBotSource.next(window.Cookiebot.consent)

            //     }
            // }
        }

        this.cookieBot$.subscribe((response) => {
            this.values = response
            this.appRef.tick()
        })

    }


    /**
     * Checks if value has been consented to in CookieBot
     * 
     * @param {string} type  necessary | preferences | statistics | marketing
     */
    cookieBotConsentValue(type: string) {

        if(isPlatformBrowser(this.platformId)) {

            let cookiebot = window.Cookiebot

            if(!!cookiebot && cookiebot.consented == true) {
                return cookiebot.consent[type]
            } else {
                return false
            }
        }
    }

}