import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { AuthenticatedUser } from "src/app/hmg-common/services/authentication/models/authenticated-user";
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { Events } from '@ionic/angular';
import {ProfileService} from '../service/profile.service'
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-profile-image',
  templateUrl: './profile-image.component.html',
  styleUrls: ['./profile-image.component.scss'],
})
export class ProfileImageComponent implements OnInit {
public userData:AuthenticatedUser;
//public src ="../assets/imgs/HMG.png";
public src :any ="";
public oldImage="";
public displayImg="";
public saveChange:any="";
public setImage:any;
// public Imge:"C:\Users\ashwaq.jaafar\Desktop\mohemmionic5\Mohem\src\assets\imgs\HMG.png";
  constructor(
    public common:CommonService,
    public ts: TranslatorService,
    public event:Events,
    public profileService:ProfileService,
    private sanitizer: DomSanitizer,

    ) {
    
        this.userData =this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA,false);

   
      this.event.subscribe("img-change", displayImg => {
        // this.user_image = "data:image/jpeg;base64"+displayImg;
         console.log("change profile photo" +displayImg);
         this.src = this.sanitizer.bypassSecurityTrustUrl("data:Image/*;base64,"+displayImg);
       });
     }
     showImg(event){
       console.log("selected profile "+event);
       this.saveChange=event;
       this.src=event;
     }
  ngOnInit() {
   // get passing  image 
   console.log("ngOnInit change profile");
   if(this.common.getUpdateImage().status){
    // this.imageSrc = this.sanitizer.bypassSecurityTrustUrl("data:Image/*;base64,"+this.cs.getUpdateImage().img);
    this.src = "data:image/png;base64,"+this.common.getUpdateImage().img;
    console.log("this.imageSrc"+ this.src);
   }else{
   
   this.src= "data:image/png;base64," + this.userData.EMPLOYEE_IMAGE;
   this.oldImage =this.src; 
   
  }
}

  updateImageProfile(){
    console.log("update");
    const srcImge=this.src.split(',')[1];
    this.displayImg=srcImge
    console.log("gallery srcImge" + srcImge);
    const body = {
      P_IMAGE: srcImge,
    };
   this.profileService.updateImageProfile(body).subscribe((result:any) =>
   {        this.handleUpdateImageProfileResult(result);
   }
   )


  }

  handleUpdateImageProfileResult(result) {
    if (this.common.validResponse(result)) {
      this.common.setUpdateImage(this.displayImg);
      this.event.publish('img-change', this.displayImg);
      let msg: string = this.ts.trPK("userProfile", "successChange");
      this.common.presentAlert(msg);
     this.common.back();
      
    } // valid it
  }// End handleWorkListButtonsResult

}
