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


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

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


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

    active = false;
    saving = false;

    package: CreateOrEditPackageDto = new CreateOrEditPackageDto();



    constructor(
        injector: Injector,
        private _packagesServiceProxy: PackagesServiceProxy
    ) {
        super(injector);
    }

    show(packageId?: number): void {

        if (!packageId) {
            this.package = new CreateOrEditPackageDto();
            this.package.id = packageId;

            this.active = true;
            this.modal.show();
        } else {
            this._packagesServiceProxy.getPackageForEdit(packageId).subscribe(result => {
                this.package = result.package;
                this.active = true;
                this.modal.show();
            });
        }
    }

    save(): void {
            this.saving = true;
            this._packagesServiceProxy.createOrEdit(this.package)
             .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();
    }
}
