import React, { useState } from "react";
import PouchDB from "pouchdb";
import { connect } from 'react-redux';
import { store } from "../redux/store";
import { useEffect } from "react";

function CommitToPouchDB(props) {

  const project = props.projects.find(
    (project) => project.projectId === props.selectedProjectId
  );

  const currentProject = project.projectName
  // use selected project to commit
  // please note project creation and management is done through project system administration web app
  const projectLink = "http://192.168.0.234:5982/" + currentProject
  // get latest version of the project from nosql database
  console.log({projectLink})
  
  const localTasksDB = new PouchDB({currentProject})
  const remoteTasksDB = new PouchDB( {projectLink} , {
    auth: {
      username: "ditswbsclient",
      password: "bluebeard",
      },
    });

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


 const commitTasks = () => {
    try {

      const result = localTasksDB
      .bulkDocs(props.tasks)
    } catch (error) {
      console.error("Error uploading new tasks to cloud: ", error);
    }
    return () => console.log('unmounting...');
  }  


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

}

export default connect(mapStateToProps)(CommitToPouchDB);

function mapStateToProps(state) {
  return {
    tasks: state.tasksReducer.tasks,
    selectedProjectId: state.projectsReducer.selectedProjectId,
    projects: state.projectsReducer.projects,
  };
}
