// Core imports
import { Component, OnInit } from '@angular/core'

// Services
import { SendCartService } from '../../services/svc.send-cart'


/**
 * @name CommentComponent
 * @description Creates an input area for comments and exposes them to the `cart`
 * @author Kasper Hansen
 * @since 07-01-2019
 */ 
@Component({
    moduleId: module.id+ '',
    selector: 'send-cart-comment',
    templateUrl: './template/t--comment.pug',
    styleUrls: ['sty.comment.scss']
})

export class CommentComponent {

    // ---- Variables ---- \\
    timeout: any
    message: string = ''
    private _sessionKey = 'comment'
    constructor(
        private _sendCart: SendCartService
    ) { }


    // ---- Lifecycle hooks ---- \\
    ngOnInit() {
        new Promise((resolve) => {
            resolve(this._sendCart.sessionStore('get'))

        }).then((response) => {

            if(!!response[this._sessionKey]) {
                this.message = response[this._sessionKey]
            }
        })
    }


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

    /**
     * Sets a cummon and exposes it to `sessionStore` and `cart` after a 0.5 second delay
     * 
     * @param event 
     */
    setComment(event) {
        this.message = event.srcElement.value

        this._sendCart.sessionStore('set', this._sessionKey, this.message)

        if(!!this.timeout)
            clearTimeout(this.timeout)

        this.timeout = setTimeout(() => {
            this._sendCart.setComment(this.message)
        }, 500)
    }
}
