import { Component, ViewChild, Injector, Output, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { RouteStopsServiceProxy, CreateOrEditRouteStopDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';
import { RouteStopContactLookupTableModalComponent } from './routeStop-contact-lookup-table-modal.component';


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

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


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

    active = false;
    saving = false;

    routeStop: CreateOrEditRouteStopDto = new CreateOrEditRouteStopDto();

    contactAddress = '';


    constructor(
        injector: Injector,
        private _routeStopsServiceProxy: RouteStopsServiceProxy
    ) {
        super(injector);
    }

    show(routeStopId?: number): void {

        if (!routeStopId) {
            this.routeStop = new CreateOrEditRouteStopDto();
            this.routeStop.id = routeStopId;
            this.contactAddress = '';

            this.active = true;
            this.modal.show();
        } else {
            this._routeStopsServiceProxy.getRouteStopForEdit(routeStopId).subscribe(result => {
                this.routeStop = result.routeStop;

                this.contactAddress = result.contactAddress;
                console.log(result);
                this.active = true;
                this.modal.show();
            });
        }
    }

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

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

        openSelectContactModal() {
        this.routeStopContactLookupTableModal.id = this.routeStop.contactId;
        this.routeStopContactLookupTableModal.displayName = this.contactAddress;
        this.routeStopContactLookupTableModal.show();
    }


        setContactIdNull() {
        this.routeStop.contactId = null;
        this.contactAddress = '';
    }


        getNewContactId() {
        this.routeStop.contactId = this.routeStopContactLookupTableModal.id;
        this.contactAddress = this.routeStopContactLookupTableModal.displayName;
    }


    close(): void {

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