import PouchDB from "pouchdb";
import { ADD_PROJECT,ADD_CDB_TASK } from "../redux/actionTypes";
import { store } from "../redux/store";
import { useEffect } from "react";




function LoadDB() {

  const projectsDB = new PouchDB("projectsDB");
  const remoteDB = new PouchDB("http://192.168.0.234:5984/ditswbs", {
    auth: {
      username: "ditswbsclient",
      password: "bluebeard",
      },
    });


  const syncHandler = projectsDB
    .sync(remoteDB, {
      live: true,
      retry: true,
    })
    .on("paused", (info) => {
      console.log("Project replication paused");
    })
    .on("active", (info) => {
      console.log("Project replication resumed");
    })
    .on("change", (change) => {
      console.log("Project change detected");
    });
  



  const initializeRedux = () => {
    try {

      const result = projectsDB
      .allDocs({ include_docs: true })
      .then((result) => {
        const projects = result.rows.map((row) => row.doc);
          projects.forEach((project) => 
          {
            store.dispatch({ type: ADD_PROJECT, project });
            let cdbsite = "http://192.168.0.234:5984"+project.projectId
            const remoteTasksDB = new PouchDB(cdbsite, {
            auth: {
              username: "ditswbsclient",
              password: "bluebeard",
            },
            })
            const taskResult = remoteTasksDB
            .allDocs({ include_docs: true })
            .then((taskResult) => {
              const tasks = taskResult.rows.map((row) => row.doc);
              tasks.forEach((task) => {
                  if(task.taskName !== null && task.taskName !== undefined) {
                  store.dispatch({ type: ADD_CDB_TASK, task })
                }
                }
            )
          });
       });
      }
      );
    } catch (error) {
      console.error("Error initialiazing redux: ", error);
    }
    return () => console.log('unmounting...');
  }  

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




export default LoadDB;




  //if(!ignore) {
  //return () => {
  //    ignore = true;
  //  };
  // Fetch initial projects

  //  const [documents, setDocuments] = useState([]);
  //  const db = new PouchDB('projectDocs');
  //  console.log ("Database created Successfully.");
  //
  //  useEffect(() => {
  //    const initializeDatabase = async () => {
  //      try {
  //        const initialProject = await db.put ({
  //          _id: "99",
  //        projects: [
  //          {
  //        id: 0,
  //        projectName: "Default",
  //        description: "Default project for testing",
  //          status: "initiated" },
  //        ]}
  //        )
  //    } catch (error) {
  //      console.error('Error initializing database: ',error)
  //    }
  //    }
  //   const fetchDocuments = async () => {
  //     try {
  //      const result = await db.allDocs({ include_docs: true });
  //       const documents = result.rows.map(row => row.doc);
  //      setDocuments(documents);
  //     } catch (error) {
  //       console.error('Error fetching documents: ', error);
  //     }
  //   };
  //
  //  initializeDatabase();
  //  fetchDocuments();
  //  }, []);


