import { Component, ViewChild, Injector, ElementRef, Output, EventEmitter } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ShippingPackageServiceProxy, CreateShippingPackageInput } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createPackageTypeModal',
    templateUrl: './create-packagetype-modal.component.html'
})
export class CreatePackageTypeModalComponent extends AppComponentBase {

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

    @ViewChild('modalCreate', {static: false}) modal: ModalDirective;
   @ViewChild('nameInput', {static: false}) nameInput: ElementRef;

    packagetype: CreateShippingPackageInput = new CreateShippingPackageInput();

    active: boolean = false;
    saving: boolean = false;

    constructor(
        injector: Injector,
        private _packagesService: ShippingPackageServiceProxy
    ) {
        super(injector);
    }

    show(): void {
        this.active = true;
        this.modal.show();
    }

    onShown(): void {
        this.nameInput.nativeElement.focus();
    }

    save(): void {
        this.saving = true;
        this._packagesService.createShippingPackage(this.packagetype)
            .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('Saved Successfully'));
                this.close();
                this.modalSave.emit(this.packagetype);
            });
    }

    close(): void {
        this.modal.hide();
        this.active = false;
    }
}