"use strict";

app.factory("vServices", function ($http) {
  //const apiIp = "http://192.168.7.143/";
  const apiIp = '';
  return {
    callApi: (url, method, dataPost, files, skipAuthorization) => {
      var fd = null,
        customHeaders = {"Content-Type": "application/x-www-form-urlencoded"},
        transformRequest = (obj) => {
          var str = [];
          for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          return str.join("&");
        };
      if (!angular.equals(files, {}) && (files)) {
        var fd = new FormData();
          if (dataPost && !angular.equals(dataPost, {}))
              for (var p in dataPost)
                  fd.append(p, dataPost[p]);
          for (var j in files)
              fd.append(j, files[j]);
        customHeaders = {"Content-Type": undefined};
        transformRequest = angular.identity;
      }
      return $http({
        method: method,
        url: apiIp + url,
        skipAuthorization: skipAuthorization,
        headers: customHeaders,
        transformRequest: transformRequest,
        data: fd ? fd : dataPost
      }).then((res) => {
        return new Promise((resolve, reject) => {
          if (res && res.data) {
            resolve(res.data);
          }
          else {
            reject(res);
          }
        });
      }).catch((error) => {
        if (error && error.data && typeof error.data === "string" && error.data.indexOf("Unauthorised request") > -1) {
          toastr.error(error.data);
        }
        else if (error && error.data && typeof error.data === "string") {
          toastr.error(error.data, error.statusText, {timeOut: 5000});
        }
        else if (error && error.data && !error.data.status) {
          toastr.error(error.data.errors, error.statusText);
        }
        else {
          //console.error(JSON.stringify(error, null, 2));
        }
        return null;
      });
    }
  };
});
