var fileUrlRegEx = /^file:\/\/(.*)/;

module.exports = {
  startupDidComplete: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "startupDidComplete",
      []);
  },

  checkForUpdates: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "checkForUpdates",
      []);
  },

  onNewVersionReady: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "onNewVersionReady",
      []);
  },

  switchToPendingVersion: function(callback, errorCallback) {
    cordova.exec(
      callback,
      (error) => {
        console.error(error);
        if (typeof errorCallback === "function") {
          errorCallback(error);
        }
      },
      "WebAppLocalServer",
      "switchPendingVersion",
      []
    );
  },

  onError: function(callback) {
    cordova.exec(
      function(errorMessage) {
        // Convert error message to a proper error object
        var error = new Error(errorMessage);
        callback(error);
      },
      console.error,
      "WebAppLocalServer",
      "onError",
      []);
  },

  localFileSystemUrl: function(fileUrl) {
    var match = fileUrlRegEx.exec(fileUrl);
    if (!match) return fileUrl;

    var path = match[1];
    return "/local-filesystem" + path;
  }
};

var fileUrlRegEx = /^file:\/\/(.*)/;

module.exports = {
  startupDidComplete: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "startupDidComplete",
      []);
  },

  checkForUpdates: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "checkForUpdates",
      []);
  },

  onNewVersionReady: function(callback) {
    cordova.exec(
      callback,
      console.error,
      "WebAppLocalServer",
      "onNewVersionReady",
      []);
  },

  switchToPendingVersion: function(callback, errorCallback) {
    cordova.exec(
      callback,
      function(error) {
        console.error(error);
        if (typeof errorCallback === "function") {
          errorCallback(error);
        }
      },
      "WebAppLocalServer",
      "switchPendingVersion",
      []
    );
  },

  onError: function(callback) {
    cordova.exec(
      function(errorMessage) {
        // Convert error message to a proper error object
        var error = new Error(errorMessage);
        callback(error);
      },
      console.error,
      "WebAppLocalServer",
      "onError",
      []);
  },

  localFileSystemUrl: function(fileUrl) {
    var match = fileUrlRegEx.exec(fileUrl);
    if (!match) return fileUrl;

    var path = match[1];
    return "/local-filesystem" + path;
  }
};

FIX - Replace fat-arrow (ES6) function with regular (ES5) function for backwards compatibility on Android 4.4.x devices (#73)