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

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

export class CustomerDataEditComponent extends FormComponent implements OnInit {

    @Output() editCustomer: EventEmitter<ICustomer> = new EventEmitter<ICustomer>();
    @Output() createCustomer: EventEmitter<ICustomer> = new EventEmitter<ICustomer>();
    @ViewChild('customerDataForm', { static: true }) customerDataForm: NgForm;

    public customer: ICustomer;
    public config: IConfig;
    public users: IUser[];
    public usersById: {};
    public consultant: IUser;

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

    ngOnInit() {
        this.customer = Factory.getEmptyCustomer();
        this.config = this.appService.getConfig();
        this.users = this.appService.getConfig().users;
        this.usersById = this.appService.getConfig().vc_user_by_id;
        this.consultant = null;
    }

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

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

    /**
     * Saves customer
     * @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.createCustomer.emit(this.customer);
            } else {
                this.editCustomer.emit(this.customer);
            }
            this.errorMsg = '';
        } else {
            this.scrollUp(this.isCreationMode ? 'customer-data-modal' : 'customer-data-edit-modal');
        }
    }

}
