
// Core imports
import { Component, OnInit, Input, Inject, PLATFORM_ID } from '@angular/core'
import { AddedToCartDialogComponent } from '../added-to-cart-dialog/cmp.added-to-cart-dialog'

// Core Services
import { BasketService } from '@k-core/services/svc.basket'
import { MatDialog } from '@angular/material'
import { isPlatformBrowser } from '@angular/common'


// Module Services


/**
 * @name Product-list-elementComponent
 * @description *watdo?*
 * @author *whodis?*
 * @since *wendis?*
 * @extends
 */
@Component({
    moduleId: module.id+ '',
    selector: 'shared-product-list-element',
    templateUrl: './template/t--product-list-element.pug',
    styleUrls: ['sty.product-list-element.scss']
})

export class ProductListElementComponent {

    // ---- Variables ---- \\
    @Input('product') product
    @Input('disabled') disabled: boolean
    // Add to cart
    quantity: number = 1
    accepted: boolean = false
    timeout: any

    productAttributeMap: Map<string, string | undefined> = new Map

    isLarge: boolean = false
    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        private _basket: BasketService,
        private _dialog: MatDialog
    ) { 
        if(isPlatformBrowser(this._platformId)) {

            this.isLarge = window.innerWidth > 1440

        }
    }

    
    // ---- Lifecycle hooks ---- \\
    ngOnInit() {


        if(!this.product.attributes) {

            // If attributes dont exist, expect them to be as regular keys on the product, locate them and squeeze them into the map
            for(let key of Object.keys(this.product)) {
                if(key.startsWith('attr_')) {
                    this.productAttributeMap.set(key.split('attr_')[1], this.product[key] ? this.product[key] : '-')
                }
            }

        } else {

            this.product.attributes.map((attr) => {
                this.productAttributeMap.set(attr.code, attr.formattedValue ? attr.formattedValue : '-')
            })
        }

        this.quantity = parseInt(this.productAttributeMap.get('colli'))

    }


    // ---- Functions ---- \\   
    changeQuantity(event) {
        this.quantity = event
    }

    addToCart(product: any, image: string, quantity: number) {

        if(!quantity) quantity = 1

        this._basket.addStep(product.sku, (this.productAttributeMap.get('colli') || 1))
        
        let productAttributes = {}s

        if(product.name) productAttributes['name'] = product.name
        if(image) productAttributes['image'] = image
        if(product.sku) productAttributes['sku'] = product.sku


        if(product.attributes) {

            for(let [k, v] of Object.entries(product.attributes)) {

                let value = v as any

                if(['EAN', 'sku', 'size'].includes(value.label) && value.value !== '-' && value.value) {
                    productAttributes[value.label] = value.value
                }
            }
        }

        if(!!product.attributes) {

            if(product.attributes.find((attribute) => attribute.code == 'color')) productAttributes['color'] = product.attributes.find((attribute) => attribute.code == 'color').formattedValue
            if(product.attributes.find((attribute) => attribute.code == 'size')) productAttributes['measurements'] = product.attributes.find((attribute) => attribute.code == 'size').formattedValue
        } else {
            if(product.attr_color) productAttributes['color'] = product.attr_color
            if(product.attr_size) productAttributes['measurements'] = product.attr_size
        }


        this._basket.addProduct('-sku--'+product.sku, quantity, productAttributes)
            .subscribe((response) => {

                if(response == 'success') {
                    this.accepted = true
            
                    if(this.timeout)
                        clearTimeout(this.timeout)
        
                    this.timeout = setTimeout(() => {
                        this.accepted = false
                    }, 1500)
        
                    // open added to cart dialog
                    this._dialog.open(AddedToCartDialogComponent)
                }
            })

    }
}
