import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { FormControl } from '@angular/forms';

import { Criterion, TimeCriterion } from '../../store/model';

@Component({
    selector: 'app-time',
    templateUrl: 'time.component.html',
    styleUrls: ['time.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimeComponent {
    @Input() id: number;
    @Input() label: string;
    @Input()
    set criterion(criterion: Criterion) {
        this.getDefault(criterion);
    }
    @Output() add: EventEmitter<TimeCriterion> = new EventEmitter();

    public hours: string[] = [];
    public minutes: string[] = [];

    hh = new FormControl();
    mm = new FormControl();

    constructor() {
        this.hours = this.initTime(24);
        this.minutes = this.initTime(60);
    }

    addCriterion() {
        const time = new TimeCriterion(this.id, this.hh.value + ':' + this.mm.value);
        this.add.emit(time);
    }

    getDefault(criterion: Criterion): void {
        if (!criterion) {
            this.hh.reset();
            this.hh.enable();
            this.mm.reset();
            this.mm.enable();
        } else {
            const c = criterion as TimeCriterion;
            this.hh.setValue(c.value.slice(0, 2));
            this.hh.disable();
            this.mm.setValue(c.value.slice(3, 5));
            this.mm.disable();
        }
    }

    initTime(time: number): string[] {
        const array: string[] = [];
        for (let i = 0; i < time; i++) {
            const t = ('0' + i).slice(-2);
            array.push(t);
        }
        return array;
    }
}