import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';


@Component({
    moduleId: module.id+ '',
    selector: 'updown',
    templateUrl: 'tpl.updown.pug',
    styleUrls: ['./sty.updown.scss']
})
export class UpDownComponent implements OnInit {


    // Dependency Injection functionality
    @Input('quantity') 
    private set _Quantity(result: string) {
        this.quantity = parseInt(result)
    }

    @Input('step')
    private set _Step(result: string) {
        if(result)
            this.step = parseInt(result)
    }

    @Output() onChange = new EventEmitter<any>()


    // Genertic variables
    timeout: any[] = []

    quantity: number = 1
    step: number = 1

    constructor() { }
    


    /**
     * Substracts this.step from value, on click
    */
    onAdd() {
        this.quantity = this.quantity + this.step
        this.onChange.emit(this.quantity)
    }

    /**
     * Substracts this.step from value, on click
    */
    onSubtract() {
        if(this.quantity > this.step){
            this.quantity = this.quantity - this.step
            this.onChange.emit(this.quantity)
        }
    }


    relayPosting: any
    /**
     * Posts the quantity after a `time` delay
     * NB: This is only for text inputting
     * 
     * @param event 
     */
    postQuantity(event) {


        if(event.srcElement.value % this.step == 0) {
            let timeoutTitle = 'post'
            let time = 800;
    
            if(!!this.timeout[timeoutTitle])
                clearTimeout(this.timeout[timeoutTitle])
    
            this.timeout[timeoutTitle] = setTimeout(() => {
    
                this.onChange.emit(this.quantity)
            }, time)
        } else {
            
            if(this.relayPosting) clearTimeout(this.relayPosting)

            this.relayPosting = setTimeout(() => {

                // If quantity is not equal to step, then find the nearest higher / lower step, if quantity becomes 0, replace it with the lowest step
                if((this.quantity % this.step) >= (this.step / 2)) {

                    this.quantity = this.quantity - (this.quantity % this.step) + this.step
                } else {

                    this.quantity = this.quantity - (this.quantity % this.step)

                    if(this.quantity == 0) this.quantity = this.step
                }

                let timeoutTitle = 'post'
                let time = 800;
        
                if(!!this.timeout[timeoutTitle])
                    clearTimeout(this.timeout[timeoutTitle])
        
                this.timeout[timeoutTitle] = setTimeout(() => {
        
                    this.onChange.emit(this.quantity)
                }, time)
            }, 800)
        }



    }

    ngOnInit() {
    }
}