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

import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup, NgForm, Validators }                               from '@angular/forms'
import { BasketService }                        from '@k-core/services/svc.basket'
import { Router, ActivatedRoute }               from '@angular/router'

import { CustomProductService }                 from '../../services/svc.custom-product'
import { resolve } from 'path';


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

export class CustomRabatComponent {


    // ---- Variables ---- \\
    // Settings
    prefix: string = '-ir'


    // Logic
    quantity: number = 1
    price: Number = null
    text: string = ''
    select: any
    discountTypes: any[]
    timeout: any
    productAdded: boolean = false
    errorTimeout
    showError: boolean = false
    errorMessage: string

    affix: string = 'kr'

    formGroup: FormGroup = new FormGroup({
        price: new FormControl('', Validators.required),
        text: new FormControl('', [Validators.required, Validators.minLength(4)]),
        select: new FormControl('', Validators.required)
    })


    constructor(
        private _router: Router,
        private _basket: BasketService,
        private _customProduct: CustomProductService
    ) {
        _customProduct.getProductSelections().then((response: any) => {

            // Set select options and select first
            if(!!response && !!response.discount_types) {
                this.discountTypes = response.discount_types

                // Patches select to have th first value of discountTypes
                this.formGroup.patchValue({'select': this.discountTypes[0].value}) 
            }
        })
    }



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

        // Sets validation based on select value, if select is changed, so will the validation, it will re-check the existing validation
        this.formGroup.controls['select'].valueChanges.subscribe((response) => {

            if(response.includes('percent')) {
                this.formGroup.controls['price'].setValidators([Validators.required, Validators.min(0.1), Validators.max(100)])

                this.affix = '%'
            } else {
                this.formGroup.controls['price'].setValidators([Validators.required, Validators.minLength(1)])
                
                this.affix = 'kr'
            }

            this.formGroup.patchValue({price: this.formGroup.controls['price'].value})
        })
    }




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

    /**
     * Gets a discount hash, submits the CustomProduct to `BasketService`,
     * and then shows a message that the discount has been added.
     */
    setIndividualCoupon() {
        let value = this.formGroup.value

        // Reset errors
        this._resetErrorMessage()

        // Prepare discount object
        let object = {
            title: value.text,
            price: value.price,
            type: value.select,
            priority: 40,
            stopped: true
        }

        // Get hash
        this._customProduct.getDiscountHash(object).then((response: any) => {


            if(!!response.data && !!response.data.hash) {
                let preparedElement = `${this.prefix}--${response.data.hash}`
        
                // Set discount

    
                    this._basket.addProduct(preparedElement, this.quantity, object)
                        .subscribe((response) => {
                            if(response == 'success') {

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

                
            }
            else {
                throw 'could not get hash from server, please try again'
            }
        })
        .catch((err) => {
            this._setErrorMessage(err)
        })

    }

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

    //     this._basket.addProduct('-sku--'+product.sku, quantity, {name: product.name, image: image})
    //         .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)
    //             }
    //         })

    // }
    /**
     * 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
    }


    /**
     * Set error message and show message container
     * 
     * @param message
     * @requires toggleErrorMessage()
     */
    private _setErrorMessage(message: string) {
        this.errorMessage = message
        this.toggleErrorMessage(true, 8000)
    }

    private _resetErrorMessage() {
        this.errorMessage = ''
        this.toggleErrorMessage(false)
    }


    /**
     * Toggles the display state of the error message container.
     * Has the option to provide a timeout to automatically hide the message on `show`
     * or delay hiding the message.
     * 
     * @param show `boolean` - show (`true`) or hide (`false`)
     * @param timeout `number` - optional timeout in milliseconds
     */
    public toggleErrorMessage(show: boolean, timeout?: number) {

        if(timeout) {
            let delayedState = !show
            clearTimeout(this.errorTimeout)

            // Show error immediately
            if(show) {
                this.showError = show
            }
            // or wait to hide
            else {
                delayedState = show
            }

            this.errorTimeout = setTimeout(() => {
                this.showError = delayedState
            }, timeout)
        }
        else {
            this.showError = show
        }
    }
}
