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


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

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


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

    active = false;
    saving = false;

    postalCode: CreateOrEditPostalCodeDto = new CreateOrEditPostalCodeDto();



    constructor(
        injector: Injector,
        private _postalCodesServiceProxy: PostalCodesServiceProxy
    ) {
        super(injector);
    }

    show(postalCodeId?: number): void {

        if (!postalCodeId) {
            this.postalCode = new CreateOrEditPostalCodeDto();
            this.postalCode.id = postalCodeId;

            this.active = true;
            this.modal.show();
        } else {
            this._postalCodesServiceProxy.getPostalCodeForEdit(postalCodeId).subscribe(result => {
                this.postalCode = result.postalCode;


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

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

			
            this._postalCodesServiceProxy.createOrEdit(this.postalCode)
             .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();
    }
}
