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

async function uploadMeasureImage(image, projectId, orderId) {
   try {
     // Ensure that folder creation and file saving are awaited
     const projectDir = await storageManager.createFolder('./storage/' + projectId.toString());
     const imagesDir = await storageManager.createFolder(path.join(projectDir, 'images'));
     const imagePath = path.join(imagesDir, `${orderId}.jpg`);
 
     // Save the file and await completion
     await storageManager.saveFile(imagePath, image.buffer);
 
     console.log("[FILE] uploadMeasureImage - Image saved to: " + imagePath);
     return imagePath;
   } catch (error) {
     console.error('Error in uploadMeasureImage:', error);
     throw error;
   }
 }

async function getMeasureImage(projectId, orderId) {
   const projectPath = `${projectId}`;
   const imagePath = `${projectPath}/${orderId}.jpg`;
   console.log("[FILE] getMeasureImage - Image path: " + imagePath);
   return storageManager.getFile(imagePath);
}

async function getNextOrderId(projectId) {
   const query = 'SELECT MAX(order_id) FROM public.measurements WHERE project_id = $1';
   const values = [projectId];
   const res = await db.query(query, values);
   console.log("[DB] getNextOrderId - Max order_id: " + res.rows[0].max);
   return res.rows[0].max + 1;
}

async function addMeasureToProject(projectId, orderId, timestamp, path, temperature, humidity) {
   const query = 'INSERT INTO public.measurements (project_id, timestamp, path, temperature, humidity, order_id) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *';
   const values = [projectId, orderId, timestamp, path, temperature, humidity];
   const res = await db.query(query, values);
   return res.rows[0];
}

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

async function getMeasurement(projectId, orderId) {
   const query = 'SELECT * FROM public.measurements WHERE project_id = $1 AND order_id = $2';
   const values = [projectId, orderId];
   const res = await db.query(query, values);
   return res.rows[0];
}

async function getMeasurementById(id) {
   const query = 'SELECT * FROM public.measurements WHERE id = $1';
   const values = [id];
   const res = await db.query(query, values);
   return res.rows[0];
}

async function updateMeasurement(projectId, orderId, timestamp, path, temperature, humidity) {
   const query = 'UPDATE public.measurements SET timestamp = $3, path = $4, temperature = $5, humidity = $6 WHERE project_id = $1 AND order_id = $2 RETURNING *';
   const values = [projectId, orderId, timestamp, path, temperature, humidity];
   const res = await db.query(query, values);
   return res.rows[0];
}

async function updateMeasurementById(id, timestamp, path, temperature, humidity) {
   const query = 'UPDATE public.measurements SET timestamp = $2, path = $3, temperature = $4, humidity = $5 WHERE id = $1 RETURNING *';
   const values = [id, timestamp, path, temperature, humidity];
   const res = await db.query(query, values);
   return res.rows[0];
}

async function deleteMeasurement(id) {
   const query = 'DELETE FROM public.measurements WHERE id = $1';
   const values = [id];
   const res = await db.query(query, values);
   return res.rows[0];
}

async function getPathFromIds(projectId, orderId) {
   console.log("Getting path from ids:", projectId, orderId);
   const query = 'SELECT path FROM public.measurements WHERE project_id = $1 AND order_id = $2';
   const values = [projectId, orderId];
   const res = await db.query(query, values);
   return res.rows[0].path;
}

async function getPathList(IdList, projectId) {
   // Convertir la chaîne de caractères en tableau
   let parsedIdList;
   try {
      parsedIdList = JSON.parse(IdList);
   } catch (e) {
      console.error("Erreur lors de la conversion de la chaîne en tableau:", e);
      return [];
   }

   console.log(parsedIdList);
   const pathList = [];
   for (const orderId of parsedIdList) {
      console.log(orderId);
      const path = await getPathFromIds(projectId, orderId);
      console.log(path);
      pathList.push(path);
   }
   return pathList;
}


export {
   uploadMeasureImage,
   addMeasureToProject,
   getNextOrderId,
   getMeasurements,
   getMeasurement,
   updateMeasurement,
   deleteMeasurement,
   getMeasureImage,
   getMeasurementById,
   updateMeasurementById,
   getPathFromIds,
   getPathList
}
