import RSVP from 'rsvp';
import run from 'ember-runloop';

let loaderCount = 0;

export function readFile(file) {
  return new RSVP.Promise((resolve, reject) => {
    let reader = new FileReader();

    loaderCount += 1;

    reader.onload = () => {
      run(null, resolve, reader.result);
    };

    reader.onerror = (error) => {
      run(null, reject, error);
    };

    reader.readAsDataURL(file);
  }).finally(() => {
    loaderCount -= 1;
  });
}

export function loadImage(src) {
  return new RSVP.Promise((resolve, reject) => {
    let image = new Image();

    loaderCount += 1;

    image.onload = () => {
      run(null, resolve, image);
    };

    image.onerror = (error) => {
      run(null, reject, error);
    };

    image.src = src;
  }).finally(() => {
    loaderCount -= 1;
  });
}

export function getLoaderCount() {
  return loaderCount;
}

export function base64EncodeImage(file) {
  return new RSVP.Promise((resolve, reject) => {
    let reader = new FileReader();

    reader.onload = () => {
      // strips meta data from string
      let encodedImageString = reader.result.replace(/data:image.*;base64,/, '');
      run(null, resolve, encodedImageString);
    };

    reader.onerror = (error) => {
      run(null, reject, error);
    };

    reader.readAsDataURL(file);
  });
}
