import { Component, ContentChild, Input } from '@angular/core';
import { AbstractControl, NgModel } from '@angular/forms';

@Component({
    selector: 'app-form-control',
    templateUrl: './form-control.component.html',
    styleUrls: ['./form-control.component.scss']
})
export class FormControlComponent {

    @Input() errorMap;
    @Input() class = '';
    @ContentChild(NgModel) model: NgModel;
    errorMessages = {
        email: 'Enter a valid email.',
        required: 'This field is required.',
        min: 'value too small',
        max: 'value too large',
        minLength: 'value too short',
        maxLength: 'value too big',
        greaterThan: 'Less than start time.'
    };

    getError(): string {
        const errors = this.control.errors;
        let error = '';
        if (errors) {
            Object
                .keys(errors)
                .some(errorKey => {
                    if (errors[errorKey]) {
                        error = this.errorMessages[errorKey] || this.errorMap[errorKey] || 'Invalid value';

                        return true;
                    }
                });
        }

        return error;
    }

    get control(): AbstractControl {
        return this.model.control;
    }

    get isHighlighted(): boolean {
        return this.control.invalid && (this.control.dirty || this.control.touched);
    }

}
