import TextCard from "./TextCard";
import "./App.css";
import { useState, useEffect } from "react";

const API_BASE_LINK = "https://copy.lucason.top";

// Get the data from the server, RETURN JS OBJECT
async function getListFromServer() {
  // make a GET request to the server
  // this doesnt technically need to be a request since theres no content or headers, but whatever
  let request = new Request(API_BASE_LINK + "/api/text", {
    method: "GET",
  });

  // fetch the data from the server
  let response = await fetch(request);
  console.log("GET Response: ", response);

  if (response.ok) {
    // get the JS object from the response
    // yes i know that says response.json, it returns a JS object for some reason
    const obj = await response.json();
    console.log("OBJECT FROM SERVER: ", obj);
    return obj;
  } else {
    // WEEE WOOO WEEEE WOOOO
    alert("ERROR: SERVER RETURNED " + response.status);
  }
}

async function deleteItem(id) {
  console.log("ID to delete: ", id);
  console.log("ID in JSON: " + JSON.stringify(id));

  // POST request that includes json of the ID (should just be a number)
  let request = new Request(API_BASE_LINK + "/api/remove", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ id }),
  });
  console.log("go");
  console.log(
    "DELETE Response: ",
    await fetch(request).then((result) => {
      return result.text();
    }),
  );
  console.log("go2");
  // reload so the up-to-date info is loaded
  location.reload();
}

async function onSubmit() {
  const encoder = new TextEncoder();

  // get the value of the nametext element, delete the input after
  let textelement = document.getElementById("nametext");
  textelement.setAttribute("value", "");

  // encode it into an array of utf-8 numbers or whatever
  const text = encoder.encode(textelement.value);

  console.log("Normal Text: ", text);
  console.log("JSON Text: ", JSON.stringify(text));

  // make a POST request that sends JSON to the server
  let request = new Request(API_BASE_LINK + "/api/add", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(text),
  });
  console.log(
    "Result: ",
    await fetch(request).then((result) => {
      return result.text();
    }),
  );
  // reload so the up-to-date info is loaded
  location.reload();
}

function App() {
  const [textList, setTextList] = useState([]);

  useEffect(() => {
    // get the JSON data from the server, store it in result
    getListFromServer().then((result) => {
      const decoder = new TextDecoder();

      // init the array to return, push each item from the data object
      let returnArray = [];
      for (let i in result) {
        console.log(result);
        console.log(result[i]);

        // convert the object array to a JS array
        var utf8Array = [];
        for (let j in result[i]) {
          utf8Array.push(result[i][j]);
        }

        // make it a Uint8Array so it can be decoded
        utf8Array = new Uint8Array(utf8Array);
        console.log("UTF8 ARRAY: " + utf8Array);

        // decode and add to return array
        let iString = decoder.decode(utf8Array);
        returnArray.push(iString);
      }

      // set textlist variable
      setTextList(returnArray);
    });
  }, [setTextList]);

  return (
    <div className="h-screen flex flex-col items-center justify-center">
      {/*center vertically    ^^^ */}
      {/*center horizontally  vvv */}
      <div className="w-screen flex flex-col justify-center items-center">
        <div className="max-w-sm max-h-svh">
          <div className="flex flex-col items-center border border-black p-2 m-1">
            <p className="m-3 mb-5 justify-self-center text-black">
              Copy Paste App
            </p>
            <div className="flex flex-row">
              <input
                className="border border-black p-1 m-1 bg-white text-black"
                id="nametext"
                type="text"
                placeholder="Put text here"
              />
              <button
                className="submitbutton border border-black p-1 m-1 bg-white text-black"
                type="submit"
                onClick={onSubmit}
              >
                Submit
              </button>
            </div>
          </div>
          <div className="flex flex-col items-stretch border border-black p-2 m-1">
            {textList.map((value, index) => {
              return (
                <TextCard
                  key={index}
                  text={value}
                  id={index}
                  deleteFunction={deleteItem}
                />
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;
