"use server"
import mysql from "mysql2/promise";
import query from '@/app/helper/query'
import fs from 'fs';
import path from 'path';
import {v4 as uuidv4} from 'uuid';

export async function createFolder(q, userId, folderName, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {
        let folderId = "folder" + uuidv4()
        let values = [folderId, userId, folderName, parentFolder, new Date()]
        await dbconnection.execute(query['SELECTFOLDER'], [userId, folderName, parentFolder]).then(async data => {
            if (data[0].length > 0) {
                throw Error("Duplicate folder")
            } else {
                await dbconnection.execute(query[q], values).catch(err => {
                    throw Error("Server error")
                })
            }
        }).catch(err => {
            dbconnection.end();
            throw Error(err.message);
        })
        let res = {
            FOLDERID: folderId,
            FOLDERNAME: folderName,
            PARENTFOLDERNAME: parentFolder
        }
        dbconnection.end();
        return res
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function getFolder(userId, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });
    try {
        
        let res = await dbconnection.execute(query['FOLDERLIST'], [userId, parentFolder]).catch(err => {
            dbconnection.end();
            throw Error(err.message);
        });
        res.pop()

        dbconnection.end();
        return res[0]
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

const getSubsequestFolder = async(userId, dbconnection, folderName, parentFolder) => {
    let pname = parentFolder + '/' + folderName
    let res = await dbconnection.execute(query['SELECTFROMPARENTNAME'], [userId, pname]).catch(err => {
        console.log(err.message)
        //throw Error(err.message);
    });
    if (res[0].length === 0) 
        return

        // console.log(res[0])
    for (let i = 0; i < res[0].length; i++) {

        await getSubsequestFolder(dbconnection, res[0][i]['FOLDERNAME'], pname)

        await dbconnection.execute(query['DELETEFOLDER'], [userId, res[0][i]['FOLDERID'],
            pname
        ]).catch(err => {
            console.log(err.message);
        })

    }
    return
}

export async function deleteFolder(userId, folderid, folderName, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        let pname = parentFolder + '/' + folderName

        await getSubsequestFolder(userId, dbconnection, folderName, parentFolder)
        await dbconnection.execute(query['DELETEFOLDER'], [userId, folderid, parentFolder])
        dbconnection.end();

        return "deleted"
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function checkFolder(userId, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        let pname = parentFolder.split('/')

        let checkF = await dbconnection.execute(query['SELECTFOLDER'], [
            userId, pname.pop(),
            pname.join('/')
        ]).catch(err => {
            console.log(err.message)
            //throw Error(err.message);
        });
        if (checkF[0].length == 0) {
            dbconnection.end();
            throw Error("Invalid Folder Path")
        }
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

const fileLocation = process.env.FOLDER_LOCATION

let content = []
export async function uploadFile(userId, file, name, type, size, pathname, last) {

    if (last) 
        content.push(file)
    else {
        let fileId = type.split('/')[0] + "-" + uuidv4() + "-" + type.split('/')[1]
        const filePath = `${fileLocation}/${userId}/${pathname}/${fileId}/${name}`;
        const folderpath = `${fileLocation}/${userId}/${pathname}/${fileId}`
        const path = `/${userId}/${pathname}/${fileId}/${name}`
       

        const dbconnection = await mysql.createConnection({
            host: process.env.MYSQL_HOST,
            port: process.env.MYSQL_PORT,
            database: process.env.MYSQL_DATABASE,
            user: process.env.MYSQL_USER,
            password: process.env.MYSQL_PASSWORD,
            namedPlaceholders: true
        });
        await dbconnection.execute(query['CHECKFILE'], [userId, name, pathname]).then(async data => {
            if (data[0].length > 0) {
                throw Error("File already exists")
            } else {

                let imagebase64Data = content.join('')
                content = []
                const buffer = Buffer.from(imagebase64Data, 'base64');

                if(!fs.existsSync(`${fileLocation}`)) fs.mkdirSync(`${fileLocation}`, {recursive: true});
                if(!fs.existsSync(`${fileLocation}/${userId}`)) fs.mkdirSync(`${fileLocation}/${userId}`, {recursive: true});
                if(!fs.existsSync(`${fileLocation}/${userId}/${pathname}`)) fs.mkdirSync(`${fileLocation}/${userId}/${pathname}`, {recursive: true});
                if(!fs.existsSync(`${fileLocation}/${userId}/${pathname}/${fileId}`)) fs.mkdirSync(`${fileLocation}/${userId}/${pathname}/${fileId}`, {recursive: true});
                try {
                    fs.writeFileSync(filePath, buffer);

                    await dbconnection.execute(query['UPLOADFILE'], [
                        fileId,
                        userId,
                        pathname,
                        name,
                        type,
                        size,
                        path,
                        new Date()
                    ]).catch(err => {
                        console.log(err.message)
                        throw Error(err.message);
                    });
                } catch (error) {
                    dbconnection.end();
                    throw Error(`Error creating page file at ${filePath}:`, error);
                }
            }

        }).catch(err => {
            dbconnection.end();
            throw Error(err.message);
        });
        content = []
        let res = {
            FILEID: fileId,
            FILENAME: name,
            FILEPATH: path,
            FILETYPE : type
        }
        dbconnection.end();
        return res
    }

}

export async function getFile(userId, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });
    try {
        const [result1,
            result2] = await Promise.all([
            dbconnection.execute(query['FILELIST'], [userId, parentFolder]),
            await dbconnection.execute(query['FOLDERLIST'], [userId, parentFolder])
        ]);
        result1.pop();
        result2.pop();
        let finalResult = {
            "file": result1[0],
            "folder": result2[0]
        }
        // let res1 = await dbconnection.execute(query['FILEFOLDERCOUNT'], [userId, parentFolder, userId, parentFolder]).catch(err => {
        //     dbconnection.end();
        //     throw Error(err.message);
        // });
        // console.log(res1)
        // console.log(finalResult) let res = await
        // dbconnection.execute(query['FILELIST'], [userId, parentFolder]).catch(err =>
        // {     dbconnection.end();     throw Error(err.message); }); res.pop()

        dbconnection.end();
        return finalResult
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function deleteFile(userId, folderid, parentFolder) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        await dbconnection.execute(query['DELETEFILE'], [userId, folderid, parentFolder])
        dbconnection.end();

        return "deleted"
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function starFile(star, userId, fileId) {
console.log(star, userId, fileId)
    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        await dbconnection.execute(query['STARTFILE'], [star, userId, fileId]).catch(error => {
            dbconnection.end();
            throw Error(error.message);
        });
        dbconnection.end();

        return "done"
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}
export async function fileSize(userId) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        let res = await dbconnection.execute(query['TOTALSIZE'], [userId])
        res.pop()

        dbconnection.end();

        return res[0]
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function getUserInfo(userId) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        let res = await dbconnection.execute(query['SELECTUSER'], [userId])
        res.pop()
        dbconnection.end();
        return res[0]
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}

export async function createUser(userId, name, provide, email) {

    const dbconnection = await mysql.createConnection({
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        namedPlaceholders: true
    });

    try {

        //USERID, USERNAME, PROVIDER, DATE, EMAIL
        await dbconnection.execute(query['CREATEUSER'], [userId, name, provide, new Date(), email]).catch(error => {
            dbconnection.end();
            throw Error(error.message);
        });
        dbconnection.end();
        return "created"
    } catch (error) {
        dbconnection.end();
        throw Error(error.message);
    }

}