import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IUser } from '../models/user';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { AppConfig } from "../shared/app.config";

@Injectable({
  providedIn: 'root',
})
export class ImageService {
  constructor(public httpClient: HttpClient, public appConfig: AppConfig) {
  }

  ApiEndpoint() {
    return this.appConfig.getConfig("apiEndPoint");
  }

  putImage(endpoint:string,blob:Blob) {
    const formData = new FormData();
    formData.append('file', blob,blob.type);
    return this.httpClient.put<any>(endpoint,formData);    
  }

  dataUrltoBlob(dataURI:string):Blob  {
    const mime = dataURI.split( ';base64,')[0].split(':')[1];
    const byteCharacters = atob(dataURI.split( ';base64,')[1]);


    const sliceSize = 512;
    const byteArrays = [];
  
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
  
      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
  
      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }
  
    const blob = new Blob(byteArrays, {type: mime});
    return blob;
  }

  blobToFile(blob:Blob, filename:string):File {
    return new File([blob],filename,{type:blob.type});
  }

  blobToDataUrl(blob:File):Promise<string> {

    return new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.addEventListener('error', () => {
        resolve("");
      });
      reader.addEventListener("load", function () {
        resolve(reader.result as string);
      }, false);
      reader.readAsDataURL(blob);
    });
  }
}
