import axios from "axios";
import { createItem } from "./items";

export const importRooms = async (data) => {
  try {
    const parsed = JSON.parse(data);

    if (parsed.length === 0) {
      return false;
    }

    for (let e of parsed) {
      const room = await createRoom(e.name);

      for (let f of e.items) {
        const settings = { ...f, room: room._id };
        await createItem(settings);
      }
    }

    return true;
  } catch (err) {
    console.error(err);
    return null;
  }
};

export const exportRooms = async () => {
  try {
    const rooms = await getRooms();

    let stock = [];

    for (let room of rooms) {
      const roomData = await getRoom(room._id);

      delete roomData._id;
      delete roomData.__v;
      delete roomData.user;
      delete roomData.updatedAt;
      delete roomData.createdAt;

      await roomData.items.forEach((f) => {
        delete f.createdAt;
        delete f.image;
        delete f.invoice;
        delete f.updatedAt;
        delete f.room;
        delete f.user;
        delete f.__v;
        delete f._id;
      });

      stock.push(roomData);
    }

    const final = JSON.stringify(stock);
    return final;
  } catch (err) {
    console.error(err);
    return null;
  }
};

export const createRoom = async (name) => {
  try {
    const response = await axios.post("/room", {
      name,
    });
    return response.data;
  } catch (err) {
    console.error(err);
  }
};

export const getState = async () => {
  try {
    const response = await axios.get("/room/stats");
    return response.data;
  } catch (err) {
    console.error(err);
    return null;
  }
};

export const deleteRoom = async (id) => {
  try {
    const response = await axios.delete(`/room/${id}`);
    return response.data;
  } catch (err) {
    console.error(err);
    return null;
  }
};

export const getRooms = async () => {
  try {
    const response = await axios.get(`/room`);
    return response.data;
  } catch (err) {
    console.error(err);
    return null;
  }
};

export const getRoom = async (id) => {
  try {
    const response = await axios.get(`/room/${id}`);
    return response.data;
  } catch (err) {
    console.error(err);
    return null;
  }
};
