import { Component, EventEmitter, ElementRef, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { IncidentServiceProxy, CreateIncidentInput } from '@shared/service-proxies/service-proxies';
import { IncidentImageServiceProxy, CreateIncidentImageInput } from '@shared/service-proxies/service-proxies';
import { ImageServiceProxy, CreateImageInput } from '@shared/service-proxies/service-proxies';
import { GeocodeServiceProxy, CreateGeocodeInput } from '@shared/service-proxies/service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import * as moment from 'moment';
@Component({
    selector: 'createIncidentModal',
    templateUrl: './create-incident-modal.component.html'
})
export class CreateIncidentModalComponent extends AppComponentBase {

   @ViewChild('createModal', {static: false}) modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    //incidents: IncidentListDto[] = [];

    //incidentImages: IncidentImageListDto[] = [];

    //images: ImageListDto[] = [];
    data: any[] = [];
    
    
    uploadUrl: string;
    uploadedFiles: any[] = [];
    
    

    incidentInput: {
      id: number;
      geocodeId: number;
      content: string;
      incidentDate: string;
         
    };

    incidentDate: Date;
    incidentTime: any;

    incidentImageInput: {
      id: number;
      imageId: number;
      incidentId: number;
         
    };

    geocodeInput: {
      id: number;
      latitude: number;
      longitude: number;
    };

    active: boolean = false;
    saving: boolean = false;
    incident: CreateIncidentInput = new CreateIncidentInput();
    incidentImage: CreateIncidentImageInput = new CreateIncidentImageInput();
    image: CreateImageInput = new CreateImageInput();
    geocode: CreateGeocodeInput = new CreateGeocodeInput();
    
    constructor(
        injector: Injector,
        private _incidentService: IncidentServiceProxy,
        private _incidentImageService: IncidentImageServiceProxy,
        private _imageService: ImageServiceProxy,
        private _geocodeService: GeocodeServiceProxy
        
    ) {
        super(injector);
        this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/DemoUiComponents/UploadFiles';
    }

    show() {
        this.active = true;
        this.init();

        this.modal.show();
    }

    onShown(): void {
        //document.getElementById('valueInput').focus();
        this.data = [];
        this.incident.content = null;
        this.geocode.latitude = null;
        this.geocode.longitude = null;
        this.incidentDate = null;
        this.incidentTime = null;
        
        
    }

    init(): void {
        
    }

    save(): void {
      this.incident.incidentDate = moment.utc(moment(this.incidentDate).format('YYYY-MM-DD') + ' ' + moment(this.incidentTime).format('HH:mm:ss'));
      console.log(this.incident.incidentDate);

      console.log(this.data);
      if (this.data === undefined || this.data.length == 0) {
           
           this._geocodeService.createGeocode(this.geocode)
               .pipe(finalize(() => { this.saving = false; }))
               .subscribe( result => {
                   //this.notify.info(this.l('SavedSuccessfully'));
                   //this.close();
                   //this.modalSave.emit(null);
                   this.incident.geocodeId = result;
                   this._incidentService.createIncident(this.incident)
                       .pipe(finalize(() => { this.saving = false; }))
                       .subscribe(() => {
                           this.notify.info(this.l('SavedSuccessfully'));
                           this.close();
                           this.modalSave.emit(null);
                   });
           });
       }
       else {
          


          this._geocodeService.createGeocode(this.geocode)
              .pipe(finalize(() => { this.saving = false; }))
              .subscribe( geocodeResult => {
                  this.incident.geocodeId = geocodeResult;
                  this._incidentService.createIncident(this.incident)
                      .pipe(finalize(() => { this.saving = false; }))
                      .subscribe( incidentResult  => {

                      this.incidentImage.incidentId = incidentResult;


                      for (let item of this.data) { 

                        this.image.fileName = item.fileName;
                        this.image.base64EncodedData = item.base64EncodedData;


                         this._imageService.createImage(this.image)
                            .pipe(finalize(() => { this.saving = false; }))
                            .subscribe( imageResult  => {

                            this.incidentImage.imageId = imageResult;



                            this._incidentImageService.createIncidentImage(this.incidentImage)
                                .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();

    }


  
     // upload completed event
    //onUpload(event): void {
         //console.log(this.uploadedFiles);  
                 
                 //for (const file of event.files) { 

                      //this.saveImage(file);
                        
                        
                       
                     
                  //}

       
       
    //}

    onBeforeSend(event): void {
        event.xhr.setRequestHeader('Authorization', 'Bearer ' + abp.auth.getToken());
    }

    getFile(event): void {
      for (const file of event.files) { 
           this.getData(file);
           
             
      }
    }

    remove(event): void {
      
       
       
       //this.data = this.data.filter(item => item = event.file.name);
       
       _.remove(this.data, function (el) {
        
           return el.fileName === event.file.name;
           
        
       });
       console.log(this.data);

       
    }
   
    getData(file) {
              
              var reader:any;
              let me = this;
              reader = new FileReader();
              reader.readAsDataURL(file);
              //reader.onload = function () {
                //me.modelvalue = reader.result;
                //console.log(reader.result.toString().split(',')[1]);
                          

              //};
              reader.onload = function() {
                              //me.modelvalue = reader.result.toString().split(',')[1];
                              //me.image.fileName = file.name;
                              //me.image.base64EncodedData = me.modelvalue;
                              
                              me.data.push(      
                              { fileName: file.name, base64EncodedData: reader.result.toString().split(',')[1] });

                        
                        
                      
              };
              reader.onerror = function (error) {
                console.log('Error: ', error);
              };
             
           
        

       
    }

}
