import React, { ReactNode, useState, useEffect } from "react";
import { Outlet, useLocation } from "react-router-dom";
import { postApi } from "../apis";
import { PostType } from "../types";

interface FormType {
  state: FormData;
}

export default function Posts() {
  const [posts, setPosts] = useState<PostType[]>([]);
  const location = useLocation() as FormType;
  const formdata = location.state;

  useEffect(() => {
    getDataList();
  }, []);

  //Read
  const getDataList = async () => {
    const res = await postApi.getData();
    setPosts(res);
  };

  //Create
  const createPost = async (filelist: FileList) => {
    if (!(filelist === undefined || filelist === null)) {
      if (filelist.length === 1) {
        formdata.append("picture", filelist?.[0]);

        const res = await postApi.createFileAndPost(formdata);

        return res;
      } else {
        for (var i = 0; i < filelist.length; i++) {
          formdata.append("picture", filelist?.[i]);
        }
        const res = await postApi.createFileAndPost(formdata);

        return res;
      }
    }
  };
  //Delete
  const deletePost = async (postId: string) => {
    const res = await postApi.deletePost(postId);
    return res;
  };
  console.log("sdfa", posts);
  return <Outlet context={{ posts, createPost, deletePost }} />;
}
