const moment = require('moment');
const ProjectTask = require('../models/projectTask');

const startStopwatch = async (req, reply) => {
    try {
        const { userId, subtaskId, jobId } = req.body;
        const startTime = Math.round(moment().valueOf() / 1000);

        // 1. Check for an existing stopped stopwatch entry for this user and subtask
        const existingStoppedEntries = await ProjectTask.fetchStopwatch(userId, subtaskId, null, 0); // status 0 for stopped

        if (existingStoppedEntries && existingStoppedEntries.length > 0) {
            // If a stopped entry exists, update it to running
            const existingEntry = existingStoppedEntries[0];
            const editedElapsedTime = existingEntry.end_time - existingEntry.start_time;
            const newStartTime = Math.round(moment().valueOf() / 1000) - editedElapsedTime;
            const updatedData = {
                start_time: newStartTime,
                end_time: null, // Clear end_time as it's now running
                status: 1 // 1 for running
            };
            const result = await ProjectTask.updateStopwatch(existingEntry.id, userId, updatedData);
            reply.send({ status: 1, message: "Stopwatch resumed successfully", result: result });
        } else {
            // If no stopped entry exists, create a new one
            const stopwatchData = {
                user_id: userId,
                job_id: jobId,
                subtask_id: subtaskId,
                start_time: startTime,
                status: 1 // 1 for running
            };
            const result = await ProjectTask.addStopwatch(stopwatchData);
            reply.send({ status: 1, message: "Stopwatch started successfully", result: result });
        }
    } catch (error) {
        console.log("Start stopwatch error : ", error);
        reply.send({ status: 0, message: "Failed to start stopwatch", error: error });
    }
};

const stopStopwatch = async (req, reply) => {
    try {
        const { stopwatchId, userId } = req.body;
        const endTime = Math.round(moment().valueOf() / 1000);
        const stopwatchData = {
            end_time: endTime,
            status: 0 // 0 for stopped
        };
        const result = await ProjectTask.updateStopwatch(stopwatchId, userId, stopwatchData);
        reply.send({ status: 1, message: "Stopwatch stopped successfully", result: result });
    } catch (error) {
        console.log("Stop stopwatch error : ", error);
        reply.send({ status: 0, message: "Failed to stop stopwatch", error: error });
    }
};

const clearStopwatch = async (req, reply) => {
    try {
        const { subtaskId, userId } = req.body;
        const result = await ProjectTask.deleteStopwatchBySubtask(subtaskId, userId);        
        reply.send({ status: 1, message: "Stopwatch cleared successfully", result: result });
    } catch (error) {
        console.log("Clear stopwatch error : ", error);
        reply.send({ status: 0, message: "Failed to clear stopwatch", error: error });
    }
};

const fetchStopwatchData = async (req, reply) => {
    try {
        const { userId, subtaskId } = req.body;
        const stopwatchEntries = await ProjectTask.fetchStopwatch(userId, subtaskId);

        let totalElapsedTime = 0;
        let activeStopwatch = null;

        stopwatchEntries.forEach(entry => {
            if (entry.status === 1) { // Running
                activeStopwatch = entry;
                totalElapsedTime += moment().unix() - entry.start_time;
            } else { // Stopped
                totalElapsedTime += (entry.end_time - entry.start_time);
            }
        });

        reply.send({
            status: 1,
            message: "Stopwatch data fetched successfully",
            result: stopwatchEntries,
            totalElapsedTime: totalElapsedTime,
            activeStopwatch: activeStopwatch
        });
    } catch (error) {
        console.log("Fetch stopwatch data error : ", error);
        reply.send({ status: 0, message: "Failed to fetch stopwatch data", error: error });
    }
};

const updateStopwatchEntry = async (req, reply) => {
    try {
        const { stopwatchId, userId, updateData } = req.body;

        // 1. Fetch the existing stopwatch entry to get its job_id and subtask_id
        const existingEntries = await ProjectTask.fetchStopwatch(userId, null, stopwatchId); 
        if (!existingEntries || existingEntries.length === 0) {
            return reply.send({ status: 0, message: "Stopwatch entry not found" });
        }
        const existingEntry = existingEntries[0]; 

        const newElapsedTime = updateData.total_time; // This is the value from the frontend (in seconds)
        
        // 2. Delete the existing stopwatch entry
        await ProjectTask.deleteStopwatchByStopwatchId(stopwatchId, userId);

        // 3. Create a new stopwatch entry with the updated total time
        const newStartTime = Math.round(moment().unix() - newElapsedTime); // Calculate start time based on new total time
        const newEndTime = Math.round(moment().unix()); // Set end time to current time or adjust as needed

        const newStopwatchData = {
            user_id: userId,
            job_id: existingEntry.job_id,
            subtask_id: existingEntry.subtask_id,
            start_time: newStartTime,
            end_time: newEndTime,
            status: 0 // New entry is considered stopped after editing
        };
        
        const result = await ProjectTask.addStopwatch(newStopwatchData);
        reply.send({ status: 1, message: "Stopwatch entry updated successfully", result: result });
    } catch (error) {
        console.log("Update stopwatch entry error : ", error);
        reply.send({ status: 0, message: "Failed to update stopwatch entry", error: error });
    }
};

module.exports = {
    startStopwatch,
    stopStopwatch,
    clearStopwatch,
    fetchStopwatchData,
    updateStopwatchEntry
};
