import {
    AfterViewChecked,
    Component,
    ElementRef,
    EventEmitter,
    Injector,
    Output,
    ViewChild,
    OnInit
} from '@angular/core';
import {
    AppConsts
} from '@shared/AppConsts';
import {
    AppComponentBase
} from '@shared/common/app-component-base';
import {
    LocationServiceProxy,
    RouteServiceProxy,
    CreateRouteTemplateInput,
    NameValueOfString,
    RouteTemplateServiceProxy,
    UpdateRouteTemplateInput,
    RouteTemplateTypeServiceProxy,
    LocationListDto,
    RouteTemplateTypeListDto
} from '@shared/service-proxies/service-proxies';
import {
    ModalDirective
} from 'ngx-bootstrap';

import * as _ from 'lodash';
import {
    finalize
} from 'rxjs/operators';
import * as moment from 'moment';
declare var $: any;

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

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

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

    locations: LocationListDto[] = [];
    templateTypes: RouteTemplateTypeListDto[] = [];
    /**** VARIABLES ****/
    create: boolean;
    active = false;
    saving = false;

    /**** CREATE LOCATION ****/

    txtLocation: any;
    txtTemplateType: any;
    startTime: any;
    endTime: any;
    txtTemplateName: string;

    /**** AUTO RESULT ****/
 
    filteredLocation: any;
    filteredTemplateType: any;
    resultLocation: any;
    resultTemplateType: any;


    /**** VARIABLE RESULTS ****/
    profilePicture: string;
    dataLocation: any;
    dataVehicle: any;
    fresult: any;
    aResult: any;
    idUpdate: number;
    currentDateTime: Date;

    defaultTemplateType: any;

    constructor(
        injector: Injector,
        private _locationServiceProxy: LocationServiceProxy,
        private _routeServiceProxy: RouteServiceProxy,
        private _routeTemplateServiceProxy: RouteTemplateServiceProxy,
        private _routeTemplateTypeServiceProxy: RouteTemplateTypeServiceProxy
    ) {
        super(injector);
    }

    show(id: any, loadObject: any): void {
          
        this.active = true;
        this.init();
        this.create = id ? false: true;
        this.currentDateTime = moment(moment().toISOString()).toDate();
        this.idUpdate = 0;
        let that = this;
        if (!this.create) {
            // Thu Aug 15 2019 21:00:32 GMT+0800 (Philippine Standard Time)
            this._routeTemplateServiceProxy.getRouteTemplatePaged(id,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined)
                .subscribe(result => {
                        this._routeTemplateTypeServiceProxy.getRouteTemplateType(result.items[0].routeTemplateTypeId, undefined, undefined, undefined, undefined).subscribe(routeTemplateType => {
                            this.idUpdate = result.items[0].id;                  
                            this.txtLocation = result.items[0].location.id;
                            // this.locations = result.items[0].location;
                            this.txtTemplateType = routeTemplateType.items[0]['id'];
                            this.txtTemplateName = result.items[0].name;
                            this.startTime = moment(moment(this.currentDateTime).format('ddd MMM DD YYYY') + ' ' + result.items[0].startTime + ':00').toDate();
                            this.endTime = moment(moment(this.currentDateTime).format('ddd MMM DD YYYY') + ' ' + result.items[0].endTime + ':00').toDate();
                            that.modal.show();
                            // loadObject.hideLoadingIndicator();
                    });
                });
        } else {
            this.clearField();
            that.modal.show();
            // this.spinnerService.hide();
            
        }

        this.getLocations();
        this.getRouteTemplateType();
        
    }

    onShown(): void {
        //this.clearField();
       
        $('.kt-select2').select2();
        
    }

    init(): void {

    }
    ngOnInit(){
        // this.getLocations();
      
        // $('.kt-select2').select2({ 
        //     dropdownParent: $('#createOrEditModal'),
        //     placeholder: "Select.."
        // });
        // console.log('ON SHOWN');


        
    }
    
    getLocations() {
        let that = this;
        this._locationServiceProxy.getLocation(undefined, undefined, undefined, undefined, undefined)
            .subscribe(result => {

                that.locations = result.items;
            });
    }
    
     getRouteTemplateType(): void {
        let that = this;
        that._routeTemplateTypeServiceProxy.getRouteTemplateType(undefined, undefined, undefined, undefined, undefined).subscribe(result =>{
            that.templateTypes = result.items;
        });
    }

    filterLocationTemplate(event): void {
        this._locationServiceProxy.getLocation(undefined, event.query, undefined, undefined, undefined).subscribe(routeLocationResult => {
            this.filteredLocation = routeLocationResult.items;
        });
    }

    filterTemplateType(event): void {
        this._routeTemplateTypeServiceProxy.getRouteTemplateType(undefined, event.query, undefined, undefined, undefined).subscribe(routeTemplateType => {
            this.filteredTemplateType = routeTemplateType.items;
        });
    }

    save(): void {
        let input = new CreateRouteTemplateInput();
        this.resultTemplateType = this.txtTemplateType;
        input.locationId =   Number((<HTMLInputElement>document.getElementById('txtLocation')).value); //this.txtLocation;
        input.routeTemplateTypeId =   Number((<HTMLInputElement>document.getElementById('txtTemplateType')).value); //this.txtTemplateType;
        input.startTime = moment(this.startTime).format('HH:mm:ss');
        input.endTime = moment(this.endTime).format('HH:mm:ss');
        input.name = this.txtTemplateName;
       
        this._routeTemplateServiceProxy.createRouteTemplate(input)
            .pipe(finalize(() => {
                this.saving = false;
            }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });

    }

    update(): void {
        let input = new UpdateRouteTemplateInput();
        
        //this.resultLocation = this.txtLocation;
        //this.resultTemplateType = this.txtTemplateType;

        input.id = this.idUpdate;
       
        input.locationId = Number((<HTMLInputElement>document.getElementById('txtLocation')).value); 
        input.routeTemplateTypeId =   Number((<HTMLInputElement>document.getElementById('txtTemplateType')).value);
        

        input.startTime = moment(this.startTime).format('HH:mm:ss');
        input.endTime = moment(this.endTime).format('HH:mm:ss');
        
        input.name = this.txtTemplateName;
       

        this._routeTemplateServiceProxy.updateRouteTemplate(input)
            .pipe()
            .subscribe(() => {
                console.log(input);
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }
    clearField() {
        this.txtTemplateName = null;
        this.txtLocation = null;
        this.txtTemplateType = null;
        this.startTime = null;
        this.endTime = null;
    }

    saveData() {
        if (this.create) {
            this.save();
        } else {
            this.update();
        }
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }


}