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

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

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

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

    date = new FormControl('');
    hh = new FormControl();
    mm = new FormControl();
    isValidFields = false;
    datetime: Date = new Date();

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

    addCriterion() {
        const fd = new DatetimeCriterion(this.id, this.datetime);
        this.add.emit(fd);
    }

    getDefault(criterion: Criterion): void {
        if (!criterion) {
            this.date.setValue('');
            this.date.enable();
            this.hh.reset();
            this.hh.enable();
            this.mm.reset();
            this.mm.enable();
            this.isValidFields = false;
        } else {
            const c = criterion as DatetimeCriterion;
            const hour = ('0' + (c.value.getHours())).slice(-2);
            const minute = ('0' + (c.value.getMinutes())).slice(-2);
            this.date.setValue(c.value);
            this.date.disable();
            this.hh.setValue(hour);
            this.hh.disable();
            this.mm.setValue(minute);
            this.mm.disable();
            this.isValidFields = true;
        }
    }

    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;
    }

    change(): void {
        if (!this.date.value || !this.hh.value || !this.mm.value) {
            this.isValidFields = false;
        } else {
            this.isValidFields = true;
            this.datetime.setFullYear(
                this.date.value.getFullYear(),
                this.date.value.getMonth(),
                this.date.value.getDate());
            this.datetime.setHours(
                this.hh.value,
                this.mm.value);
        }
    }
}