/**
 * Made by mkcomponent.sh
 * * Change to Fileheader info *
*/

import { Component, OnInit, OnChanges, Inject } from '@angular/core'
import { NgForm }                               from '@angular/forms'
import { Router }                               from '@angular/router'
import { BasketService }                        from '@k-core/services/svc.basket'
import { CustomProductService }                 from '../../services/svc.custom-product'

@Component({
    moduleId: module.id+ '',
    selector: 'custom-product-createProduct',
    templateUrl: './template/t--createProduct.pug',
    styleUrls: ['sty.createProduct.scss']
})

export class CreateproductComponent {

    // ---- Variables ---- \\
    select: any
    quantity: number = 1
    configurations

    timeout: any
    productAdded: boolean = false

    constructor(
        private _router: Router,
        private _basket: BasketService,
        private _customproduct: CustomProductService
    ) {


        _customproduct.getProductSelections().then((response: any) => {

            if(!!response && !!response.products) {

                this.configurations = response.products
    
                this.select = this.configurations[0].value
            }
        })



    }


    // ---- Lifecycle hooks ---- \\


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

    /**
     * Submits the CustomProduct to `BasketService`
     * 
     * @param {NgForm} form 
     */
    setCustomProduct(form: NgForm) {
        let value = form.value

        let object = {
            title: value.text,
            type: value.type,
            price: value.price
        }

        this._basket.addProduct(`-dv--${value.text}`, this.quantity, object)
            .subscribe((response) => {
                if(response == 'success') {

                    this.productAdded = true
        
                    if(!!this.timeout)
                        clearTimeout(this.timeout)
        
                    this.timeout = setTimeout(() => {
                        this.productAdded = false
                    }, 2000)
                }
            })

    }


    setQuantity(event) {
        this.quantity = event
    }


    /**
     * Checks if all values are set, if they are, enable button
     * 
     * @param {NgForm} form
     */
    checkForm(form: NgForm) {

        let result = false

        for(let key of Object.keys(form.value)) {

            if(!form.value[key]) {
                result = true
            }
        }

        return result
    }
}