import { Component, ViewChild, Injector, Output, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { PreferencesServiceProxy, CreateOrEditPreferenceDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';


@Component({
    selector: 'createOrEditPreferenceModal',
    templateUrl: './create-or-edit-preference-modal.component.html'
})
export class CreateOrEditPreferenceModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;


    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    preference: CreateOrEditPreferenceDto = new CreateOrEditPreferenceDto();



    constructor(
        injector: Injector,
        private _preferencesServiceProxy: PreferencesServiceProxy
    ) {
        super(injector);
    }

    show(preferenceId?: number): void {

        if (!preferenceId) {
            this.preference = new CreateOrEditPreferenceDto();
            this.preference.id = preferenceId;

            this.active = true;
            this.modal.show();
        } else {
            this._preferencesServiceProxy.getPreferenceForEdit(preferenceId).subscribe(result => {
                this.preference = result.preference;


                this.active = true;
                this.modal.show();
            });
        }
    }

    save(): void {
            this.saving = true;

			
            this._preferencesServiceProxy.createOrEdit(this.preference)
             .pipe(finalize(() => { this.saving = false;}))
             .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
             });
    }







    close(): void {

        this.active = false;
        this.modal.hide();
    }
}
