import { Injectable } from '@angular/core'

// Services
import { BasketService } from '@k-services/svc.basket'

// Settings
import { currency } from '@k-settings/store-helper'


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


@Injectable()
export class DataLayerTrackingService {

	// ---- Variables ---- \\
    productsToDatalayer = []
    calctotal: number = 0
	


	constructor(
		private _basket: BasketService
	) { }





	// ---- Functions ---- \\

	/**
     * Adds a DataLayer, from Analytics basic eCommerce tracking
     * Uses `orderId` from `queryParams` to set transaction, then populates
     * the rest of the values through `this.basket`
     * *! Be aware, this only pushes dataLayer if `products` exist
     * 
     * @todo Fix `dataLayer` not existing on `window` type
     * @param products `this.basket` as `Object`
     * @param transactionId `queryParam.params['orderId']` response
     */
    addDataLayer(products, transactionId): void {

        new Promise((resolve) => {
            let index = 0

            for(let product of products) {
    
                this._basket.getProductById(product.id).then((response) => {
    
                    this.productsToDatalayer.push({
                        'sku': response.sku,
                        'name': response.name,
                        'category': response.categories[0].name,
                        'price': parseFloat(response.price),
                        'quantity': parseFloat(product.quantity)
                    })
    
                    this.calctotal += (parseFloat(response.price) * parseFloat(product.quantity))


                    // Resolve once all products have been added
                    index++
                    if(index >= products.length) {
                        resolve()
                    }
                })
            }

        }).then(() => {
    
            let dataLayer = window.dataLayer || []

            dataLayer.push({
                'event': 'custom.transaction',
                'transactionId': transactionId,
                // 'transactionAffiliation': 'Acme Clothing',
                'transactionTotal': this.calctotal,
                'transactionCurrency': currency,
                // 'transactionTax': 1.29,
                // 'transactionShipping': 5,
                'transactionProducts': this.productsToDatalayer,
            })
        })


    }
}