import { UserInfo } from 'app/models/userInfo.model';
import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { PgUserInfoDtlsList } from 'app/models/employee.model';
import { DomSanitizer } from '@angular/platform-browser';
import { SafeUrl } from '@angular/platform-browser/src/security/dom_sanitization_service';
import * as html2canvas from 'html2canvas';
import { AuthService } from 'app/services/auth.service';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { ToastsManager } from 'ng2-toastr';
import { delayWhen } from 'rxjs/operator/delayWhen';
import { LocalStorageService } from 'angular-2-local-storage/dist';
import { LogoutDataService } from 'app/employee/employee-dashboard/employee-logout/logout-data.service';




@Component({
  selector: 'app-employee-profile-description',
  templateUrl: './employee-profile-description.component.html',
  styleUrls: ['./employee-profile-description.component.scss']
})
export class EmployeeProfileDescriptionComponent implements OnInit {
  @Input() data: { pictureImage: SafeUrl, UserInfoDtls: PgUserInfoDtlsList };
  @Output() hover = new EventEmitter<boolean>();

  modifyPhoto = false;
  imageBack: SafeUrl;
  userInfo: UserInfo;

  private profilePic: File;

  constructor(
    private sanitizer: DomSanitizer,
    private employeeService: EmployeeHttpService,
    private authService: AuthService,
    protected localStorageService: LocalStorageService,
    private toastr: ToastsManager,
    private logoutDataService: LogoutDataService
  ) { }
  @ViewChild('imagePhoto') imagePhoto: ElementRef;
  @ViewChild('inputFile') inputFile: ElementRef;
  ngOnInit() {
    this.userInfo = this.localStorageService.get<UserInfo>('userInfo');
  }

  changeProfilePhoto(f: HTMLInputElement) {
    this.modifyPhoto = true;
    const reader = new FileReader();

    this.profilePic = f.files[0];

    reader.addEventListener('load', () => {
      this.imageBack = this.data.pictureImage;
      this.data.pictureImage = reader.result;
      this.dragElement(this.imagePhoto);
    }, false);

    if (f.files[0]) {
      reader.readAsDataURL(f.files[0]);
    }
    const formData = new FormData();
    formData.append('file', f.files[0]);

  }

  savePhoto() {
    this.modifyPhoto = false;
    this.inputFile.nativeElement.value = '';

    let formData: FormData = new FormData();

    formData.append('file', this.profilePic, this.profilePic.name);

    this.employeeService.uploadEmployeeRelatedFile(formData).subscribe(r => {

      this.employeeService.uploadProfile(this.data.UserInfoDtls.pgUserInfoMstr.userInfoMstrId, {
        fileId: r.fileId,
        fileName: r.fileName
      })
        .finally(() => this.cancelPhoto())
        .subscribe(rr => {
          const reader = new FileReader();

          reader.addEventListener('load', () => {
            this.data.pictureImage = reader.result;
            this.imagePhoto.nativeElement.style.left = null;
            this.imagePhoto.nativeElement.style.top = null;
          }, false);

          reader.readAsDataURL(this.profilePic);

          this.userInfo.profileImgId = r.fileId;
          this.logoutDataService.setProfileImg(this.data.pictureImage);
          this.localStorageService.set('userInfo', this.userInfo);

          this.toastr.clearAllToasts();
          this.toastr.success('Profile Image Updated');
        }, err => {
          this.data.pictureImage = this.imageBack;
          this.modifyPhoto = false;
          this.toastr.clearAllToasts();
          this.toastr.error('was wrong photo', 'Save Photo');
        });
    }, err => {
      this.data.pictureImage = this.imageBack;
      this.modifyPhoto = false;
      this.toastr.clearAllToasts();
      this.toastr.error('was wrong photo', 'Save Photo');
    });


    // html2canvas(this.imagePhoto.nativeElement, { logging: false })
    //   .then((canvas: HTMLCanvasElement) => {

    //     canvas.toBlob(b => {

    //       const fil = new File([b], 'thumbiels.png', { type: 'image/png' });
    //       const formData = new FormData();
    //       formData.append('file', fil);

    //       this.employeeService.uploadEmployeeRelatedFile(formData)
    //         .subscribe(r => {

    //           this.employeeService.uploadProfile(this.data.UserInfoDtls.pgUserInfoMstr.userInfoMstrId, {
    //             fileId: r.fileId,
    //             fileName: r.fileName
    //           })
    //             .finally(() => this.cancelPhoto())
    //             .subscribe(rr => {
    //               let syncSholudContinues = false;
    //               const reader = new FileReader();
    //               reader.addEventListener('load', () => {
    //                 this.data.pictureImage = reader.result;
    //                 this.imagePhoto.nativeElement.style.left = null;
    //                 this.imagePhoto.nativeElement.style.top = null;
    //               }, false);
    //               reader.readAsDataURL(b);
    //               this.userInfo.profileImgId = r.fileId;
    //               this.localStorageService.set('userInfo', this.userInfo);
    //               this.toastr.clearAllToasts();
    //               this.toastr.success('Profile Image Updated');
    //             }, err => {
    //               this.data.pictureImage = this.imageBack;
    //               this.modifyPhoto = false;
    //               this.toastr.clearAllToasts();
    //               this.toastr.error('was wrong photo', 'Save Photo');
    //             });
    //         }, err => {
    //           this.data.pictureImage = this.imageBack;
    //           this.modifyPhoto = false;
    //           this.toastr.clearAllToasts();
    //           this.toastr.error('was wrong photo', 'Save Photo');
    //         });
    //     });
    //   });
  }
  cancelPhoto() {

    this.data.pictureImage = this.imageBack;

    this.imagePhoto.nativeElement.style = null;
    this.modifyPhoto = false;

    this.inputFile.nativeElement.value = '';

    this.closeDragElement(this.imagePhoto)();
  }
  private dragElement(el: ElementRef) {
    let offset: number[];
    const _el = el.nativeElement as HTMLImageElement;
    const dragMouseDown = (e) => {
      e.stopPropagation();
      e = e || window.event;

      // get the mouse cursor position at startup:

      offset = [
        el.nativeElement.offsetLeft - e.clientX,
        el.nativeElement.offsetTop - e.clientY
      ];

      // call a function whenever the cursor moves:
      document.body.onmousemove = elementDrag;

    };

    const elementDrag = (e) => {
      e.stopPropagation();
      e = e || window.event;
      // calculate the new cursor position:
      const mousePosition = {

        x: e.clientX,
        y: e.clientY

      };

      el.nativeElement.style.left = (mousePosition.x + offset[0]) + 'px';
      el.nativeElement.style.top = (mousePosition.y + offset[1]) + 'px';

    };
    const closeDrag = () => {
      /* stop moving when mouse button is released:*/
      document.body.onmousemove = null;
      _el.onmousewheel = null;
    };

    // disabling drag
    // _el.onmouseup = closeDrag;
    // _el.onmousedown = dragMouseDown;
    // document.body.onmouseup = closeDrag;

    // _el.onmouseout = () => _el.onmousewheel = null;



  }


  closeDragElement(el: ElementRef) {
    return () => {
      const _el = el.nativeElement as HTMLImageElement;
      /* stop moving when mouse button is released:*/
      document.body.onmousemove = null;
      _el.onmousewheel = null;
      _el.onmousedown = null;
      _el.onmouseup = null;
    };
  }
}
