import storageManager from '../data/storageManager.js';
import db from '../../db.js';

function createProjectDirectory(projectId) {
   const projectPath = `${projectId}`;
   storageManager.createFolder(projectPath);
   storageManager.createFolder(`${projectPath}/images`);
   storageManager.createFolder(`${projectPath}/videos`);
   console.log("[FILE] createProjectDirectory : " + projectPath);
}

function deleteProjectDirectory(projectId) {
   const projectPath = `${projectId}`;
   storageManager.deleteFolder(projectPath);
   console.log("[FILE] deleteProjectDirectory : " + projectPath);
}

async function getAllProjects() {
   const query = 'SELECT * FROM public.projects';
   const res = await db.query(query);
   console.log("[DB] getAllProjects : ", res.rows);
   return res.rows;
}

async function getProjectById(projectId) {
   const query = 'SELECT * FROM public.projects WHERE id = $1';
   const values = [projectId];
   const res = await db.query(query, values);
   console.log("[DB] getProjectById : ", res.rows[0]);
   return res.rows[0];
}

async function createProject(name, description, start_date, status) {
   const query = 'INSERT INTO public.projects (name, description, start_date, status) VALUES ($1, $2, $3, $4) RETURNING *';
   const values = [name, description, start_date, status];
   const res = await db.query(query, values);
   console.log("[DB] createProject : ", res.rows[0]);
   return res.rows[0];
}

async function editProjectById(projectID, name, description, startDate, status) {
   const query = 'UPDATE public.projects SET name = $1, description = $2, start_date = $3, status = $4 WHERE id = $5 RETURNING *';
   const values = [name, description, startDate, status, projectID];
   const res = await db.query(query, values);
   console.log("[DB] editProjectById : ", res.rows[0]);
   return res.rows[0];
}

async function deleteProjectById(projectId) {
   const query = 'DELETE FROM public.projects WHERE id = $1';
   const values = [projectId];
   console.log("[DB] deleteProjectById : ", values);
   await db.query(query, values);
}

async function getVideosByProjectId(projectId) {
   const query = 'SELECT * FROM public.videos WHERE project_id = $1';
   const values = [projectId];
   const res = await db.query(query, values);
   console.log("[DB] getVideosByProjectId : ", res.rows);
   return res.rows;
}

async function getMeasurementsByProjectId(projectId) {
   const query = 'SELECT * FROM public.measurements WHERE project_id = $1';
   const values = [projectId];
   const res = await db.query(query, values);
   console.log("[DB] getMeasurementsByProjectId : ", res.rows);
   return res.rows;
}

export {
   createProjectDirectory,
   deleteProjectDirectory,
   getAllProjects,
   getProjectById,
   createProject,
   editProjectById,
   deleteProjectById,
   getVideosByProjectId,
   getMeasurementsByProjectId
};
