import axios from "axios";

export const getSuperboxApiConfig = (address) => {
  const PORT = 8000;
  const BASE_ROUTE = "/api/v1";
  const LOGIN_ROUTE = BASE_ROUTE + "/auth/login";
  const LOGOUT_ROUTE = BASE_ROUTE + "/auth/logout";
  const CAMERA_ROUTE = BASE_ROUTE + "/camera/cameras";
  const EVENTS_ROUTE = BASE_ROUTE + "/event/events";
  const ALGORITHM_ROUTE = BASE_ROUTE + "/algorithms";
 
  let addr = address;
  if (!addr) {
    addr = window.location.host.replace(/:\d+/, "");
    console.log("No address provided, using " + addr);
  }
  const superboxAddress = "http://" + addr + ":" + PORT.toString();

  return {
    base: superboxAddress + BASE_ROUTE,
    login: superboxAddress + LOGIN_ROUTE,
    logout: superboxAddress + LOGOUT_ROUTE,
    cameras: superboxAddress + CAMERA_ROUTE,
    events: superboxAddress + EVENTS_ROUTE,
    algorithms: superboxAddress + ALGORITHM_ROUTE,
  };
  /*return {
    base: "/api/v1",
    login: "/api/v1/auth/login",
    logout: "/api/v1/auth/logout",
    cameras: "/api/v1/camera/cameras",
    events: "/api/v1/event/events",
  };*/
};

axios.defaults.withCredentials = true;
export const login = (username, password, address = null) => {
  return new Promise((resolve, reject) => {
    const api = getSuperboxApiConfig(address);
    axios
      .post(
        api.login,
        {
          username: username,
          password: password,
          cookieless: false,
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((res) => {
        if (res.data.err.ec === 0) {
          resolve(res.data.ret.token);
        }
        reject(res.data.err);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const getCameras = (token, address = null) => {
  return new Promise((resolve, reject) => {
    const api = getSuperboxApiConfig(address);
    axios
      .get(api.cameras, {
        withCredentials: true,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        if (res.data.err.ec === 0) {
          resolve(res.data.ret.results);
        }
        reject(res.data.err);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const getEvents = (token, address = null, pageSize = 20, currentPage = 1) => {
  return new Promise((resolve, reject) => {
    const api = getSuperboxApiConfig(address);
    const offset = (currentPage - 1) * pageSize;
    const params = new URLSearchParams({ limit: pageSize, offset });
    const urlWithParams = `${api.events}?${params.toString()}`;
    // console.log("urlWithParams>>>>>>>>>>>>>>>>>", urlWithParams);
    axios
      .get(urlWithParams, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        if (res.data.err.ec === 0) {
          resolve({
            tableData: res.data.ret.results,
            totalItems: res.data.ret.count
          });
        }
        reject(res.data.err);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const getAlgorithms = (token, address = null) => {
  return new Promise((resolve, reject) => {
    const api = getSuperboxApiConfig(address);
    axios
      .get(api.algorithms, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        if (res.data.err.ec === 0) {
          resolve(res.data.ret);
        }
        reject(res.data.err);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

var codeNameMap = {};

export const initCodeNameMap = async (token, address = null) => {
  try {
    const algorithms = await getAlgorithms(token, address);
    algorithms.forEach((algorithm) => {
      codeNameMap[algorithm.code_name] = algorithm.name;
    });
    return true;
  } catch (err) {
    console.log(err);
    return false;
  }
};

export const codenameTranslate = (codeName) => {
  return codeNameMap[codeName];
};

export default {
  login,
  getCameras,
  getEvents,
  getSuperboxApiConfig,
  initCodeNameMap,
  codenameTranslate,
  getAlgorithms,
};
