import { Component, ViewChild, Injector, ElementRef, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    IncidentServiceProxy, UpdateIncidentInput
} from '@shared/service-proxies/service-proxies';
import {
    GeocodeServiceProxy, UpdateGeocodeInput
} 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 * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';

import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
    selector: 'editIncidentModal',
    templateUrl: './edit-incident-modal.component.html'
})
export class EditIncidentModalComponent extends AppComponentBase {

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

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

  incident: UpdateIncidentInput = new UpdateIncidentInput();
  geocode: UpdateGeocodeInput = new UpdateGeocodeInput();
  
  data: any[] = [];

  uploadUrl: string;
  uploadedFiles: any[] = [];

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

  incidentDate: Date;
  incidentTime: any;

  incidentImage: CreateIncidentImageInput = new CreateIncidentImageInput();
  image: CreateImageInput = new CreateImageInput();
  

  constructor(
    injector: Injector,
    private _incidentService: IncidentServiceProxy,
    private _geocodeService: GeocodeServiceProxy,
    private _incidentImageService: IncidentImageServiceProxy,
    private _imageService: ImageServiceProxy,

  ) {
    super(injector);

     this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/DemoUiComponents/UploadFiles';
  }

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


    this._incidentService.getIncident(incidentId, undefined, undefined, undefined, undefined, undefined).subscribe((result)=> {
      console.log(result.items);
      this.incident.content = result.items[0]['content'];
      this.incident.id = result.items[0]['id'];
      this.incident.geocodeId =  result.items[0]['geocodeId'];
      this.incidentDate =  result.items[0]['incidentDate'].toDate();
      this.incidentTime =  result.items[0]['incidentDate'].toDate();
      if(result.items[0]['geocode'] != undefined) {
        this.geocode.id = result.items[0]['geocodeId'];
        this.geocode.latitude = result.items[0]['geocode']['latitude'];
        this.geocode.longitude = result.items[0]['geocode']['longitude'];
      }
     
      console.log(result.items[0]['incidentDate']);
      this.modal.show();
    });

  }

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

   this.data = [];
  }

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

    if (this.data === undefined || this.data.length == 0) {
          this._incidentService.updateIncident(this.incident)
            .subscribe(() => {
                      
                      this._geocodeService.updateGeocode(this.geocode)
                      .subscribe(() => {
                        



                        this.notify.info(this.l('SavedSuccessfully'));
                        this.close();
                        this.modalSave.emit(this.geocode);
                      });


             
            });
          this.saving = false;
       
         
    }
    else {


          this._incidentService.updateIncident(this.incident)
            .subscribe(() => {
                      
                      this._geocodeService.updateGeocode(this.geocode)
                      .subscribe(() => {
                        
                        
                          this.incidentImage.incidentId = this.incident.id;


                          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);
                                       
                                });


                            });
                              
                          }

                        //this.notify.info(this.l('SavedSuccessfully'));
                        //this.close();
                        //this.modalSave.emit(this.geocode);
                      

                      });


             
            });
          this.saving = false;

    }
  }


  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);
            };
           
         
      

     
  }

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