import {decrypt, isAuthenticated} from "./cookiehelper.js";
import {_serverUrl} from "./setting.js";
let serverUrl = _serverUrl();
let baseSessionId, baseUserInfo;
if (isAuthenticated()) {
  baseUserInfo = decrypt(document.cookie.split("=")[1]);
  baseSessionId = baseUserInfo.sessionId;
} else {
  window.location = "../login";
}
export function getData(url) {
  var datastr = null;
  var method = "GET";
  let serviceurl = serverUrl + url;

  return $.ajax({
    type: method,
    url: serviceurl,
    crossDomain: true,
    contentType: "application/json",
    cache: true,
    jsonp: false,
    data: datastr,
    beforeSend: function (xhr) {
      if (baseUserInfo != undefined && baseUserInfo != null) {
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + JSON.parse(baseUserInfo).sessionId
        );
        xhr.setRequestHeader("geoposition", 0 + ":" + 0);
      }
    },
  });
}

export function getDataObj(url, data, async, type) {
  //url, data, true, "POST"

  let serviceurl = serverUrl + url;
  return $.ajax({
    type: type,
    url: serviceurl,
    data: JSON.stringify(data),
    contentType: "application/json",
    traditional: true,
    crossDomain: true,
    async: async,
    beforeSend: function (xhr) {
      if (baseUserInfo != undefined && baseUserInfo != null) {
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + JSON.parse(baseUserInfo).sessionId
        );
        xhr.setRequestHeader("geoposition", 0 + ":" + 0);
      }
    },
  });
}

export function formatLocal(dateTime) {
  var hou = new Date(dateTime).getHours(),
    sec,
    min,
    day,
    month,
    years;
  if (hou < 24) {
    min = new Date(dateTime).getMinutes();
    if (min < 60) {
      sec = new Date(dateTime).getSeconds();
      if (sec < 60) {
        return sec + " Seconds";
      }
    } else {
      return min + " Minutes";
    }
    return hou + " Hours";
  } else {
    //24 >
    day = new Date(dateTime).getHours();
    if (day > 31) {
      // 31 day
      month = new Date(dateTime).getMonth();
      if (month > 12) {
        // 12 months
        years = new Date(dateTime).getFullYear();
        return years + " Years";
      }
      return month + " month";
    }
    return day + " day";
  }
}
