import { Injectable } from '@angular/core';

import { server } from '@k-settings/store-helper'
import { scope } from '@k-settings/app-setup.js'

import { PLATOProducts } from '@k-core/interfaces/Plato'

// As default OAuthToken - however, we're using a minimal version with only access_token
interface OAuthToken {
    access_token: string;
    expires_in?: number;
    scope?: string;
    token_type?: string;
}

@Injectable()
export class PlatoConfiguratorService {
	
    environment = scope == 'production' || scope == 'staging' ? 'prod' : 'acceptance'
    catalogUri = `https://bmscatalogquery-${this.environment}.azurewebsites.net`

    // Minimal token object
    impersonatortoken: OAuthToken

    productData: PLATOProducts

    /**
     * Gets the token from backend API
     * @returns void
     */
    async getImpersonatorToken(): Promise<void> {

        return fetch(`${server}api-server/impersonatorToken`)
            .then((response) => response.text())
            .then((data: string) => {

                this.impersonatortoken = {
                    access_token: data
                }
            })
    }


    /**
     * gets list of product-ids from API, gets the max based on `size`
     */
    async getCatalog(): Promise<void> {

        const size: number = 400

        await this.getImpersonatorToken().then(() => {

            const headers = new Headers()
                headers.set('Content-Type', 'application/json')
                headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)

            return fetch(`${server}catalogapi/api/catalog/items/?pageIndex=0&pageSize=${size}`, {method: 'GET', headers: headers})
                .then(response => response.json())
                .then(data => this.productData = data)
                .then(() => console.log(this.productData))

        })
    }


    /**
     * Gets the product variant information based on a GUID
     * 
     * @param guid {string} ItemId
     * @returns 
     */
    async getVariant(guid: string): Promise<JSON> {

        return await this.getImpersonatorToken().then(() => {

            const headers = new Headers()
                headers.set('Content-Type', 'application/json')
                headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)

            return fetch(`${server}variantqueryapi/api/productvariant/${guid}`, {method: 'GET', headers: headers})
                .then(response => response.json())
        })

    }

        
    /**
     * Copies a variant with all specs
     * 
     * @param guid {string} variantId
     * @returns 
     */
    async copyVariant(guid: string): Promise<any> {
        return await this.getImpersonatorToken().then(() => {

            const headers = new Headers()
                headers.set('Content-Type', 'application/json')
                headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)
                
            return fetch(`${server}/variantcommandapi/api/productvariant/${guid}/copy`, {method: 'POST', headers: headers})
                .then(response => response.json())
        })
    }

    async getSalesPrice(guid) {
        return await this.getImpersonatorToken().then(() => {
            const headers = new Headers()

            headers.set('Content-Type', 'application/json')
            headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)

            return fetch(`${server}catalogapi/api/Articles/${guid}/salesprice`,  {method: 'GET', headers: headers})
                .then(response => response.json())

        })
    }

    async getTags() {

        let tags: any

        await this.getImpersonatorToken().then(() => {

            const headers = new Headers()
                headers.set('Content-Type', 'application/json')
                headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)

            return fetch(`${server}catalogapi/api/catalog/tags`, {method: 'GET', headers: headers})
                .then(response => response.json())
                .then((response) => tags = response)
        })

        return tags
    }

    async getCatalogByTags(tags: any) {


        let products: any
        const size: number = 400

        await this.getImpersonatorToken().then(() => {

            const headers = new Headers()
                headers.set('Content-Type', 'application/json')
                headers.set('Authorization', `Bearer ${this.impersonatortoken.access_token}`)

            return fetch(`${server}catalogapi/api/catalog/items/?pageIndex=0&pageSize=${size}&tags=${tags}`, {method: 'GET', headers: headers})
                .then(response => response.json())
                .then(data => products = data)
        })

        return products
    }
}