import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormComponent} from '../../../../components/form-component';
import {NgForm} from '@angular/forms';
import {IConfig} from '../../../../model/virtual/config';
import {AppService} from '../../../../services/app.service';
import {ScrollToService} from '@nicky-lenaers/ngx-scroll-to';
import {Factory} from '../../../../factory/factory';
import {isNull} from 'util';
import {IProduction} from '../../../../model/entities/production';

@Component({
  selector: 'app-production-data-edit',
  templateUrl: './production-data-edit.component.html',
  styleUrls: ['./production-data-edit.component.scss']
})

export class ProductionDataEditComponent extends FormComponent implements OnInit {

    @Output() editProduction: EventEmitter<IProduction> = new EventEmitter<IProduction>();
    @Output() createProduction: EventEmitter<IProduction> = new EventEmitter<IProduction>();
    @ViewChild('productionDataForm', { static: true }) productionDataForm: NgForm;

    public production: IProduction;
    public config: IConfig;

    constructor(private appService: AppService, protected scrollToService: ScrollToService) {
        super(scrollToService);
    }

    ngOnInit() {
        this.production = Factory.getEmptyProduction();
        this.config = this.appService.getConfig();
    }

    /**
     * Sets data
     * @param production
     */
    public setData(production: IProduction): void {
        this.production = production;
        this.isCreationMode = isNull(this.production.id);
        this.errorMsg = '';
        this.resetFormValidation();
    }

    /**
     * Resets Form Validation
     */
    public resetFormValidation(): void {
        this.productionDataForm.form.markAsUntouched();
    }

    /**
     * Saves production
     * @param value
     * @param valid
     */
    public onFormSubmit({value, valid}: { value: any, valid: boolean }): void {
        this.errorMsg = 'Bitte beheben Sie alle Fehler.';
        if (valid) {
            if (this.isCreationMode) {
                this.createProduction.emit(this.production);
            } else {
                this.editProduction.emit(this.production);
            }
            this.errorMsg = '';
        } else {
            this.scrollUp(this.isCreationMode ? 'production-data-modal' : 'production-data-edit-modal');
        }
    }
}
