const { app, ipcMain } = require("electron")
const fs = require('fs-extra');
const os = require('os');
const nodeDiskInfo = require('node-disk-info');
const path = require("path");

const getDocumentsPath = () => {
    const osType = os.type();
    const isWindows = osType == "Windows_NT";
    let documentsPath = app.getPath('documents');
    if (isWindows) {
        try {
            let disks = nodeDiskInfo.getDiskInfoSync();
            disks = disks.filter(disk => {
                const filesystem = disk.filesystem.toLowerCase();
                return filesystem.indexOf('local') > -1 || filesystem.indexOf('本地') > -1
            })
            let index = 0;
            if (disks.length > 1) {
                index = 1;
            }
            documentsPath = disks[index].mounted;
        } catch (e) {
            console.error(e);
        }
    }

    return documentsPath + '/FIR.AI CACHES/';
}

// 同步云端文件到本地
const saveFile = function (e, params, { store }) {
    const documentsPath = getDocumentsPath();
    const basePath = params.path + '/' + params.fileName;
    const savePath = documentsPath + basePath;

    const fileId = params.fileId;
    const key = `firCache.${fileId}`;

    const hasCache = store.get(key);

    if (hasCache && hasCache != savePath) {
        fs.remove(hasCache)
    }

    store.set(key, savePath)

    fs.outputFile(savePath, params.fileData)
        .then(res => {
            // console.log(res)
        })
        .catch(err => {
            console.error("savePath err-----")
            console.error(err)
        });
}

const getFile = function (event, { fileId }, { store }) {
    try {
        const key = `firCache.${fileId}`;
        const hasCache = store.get(key);
        if (hasCache) {
            return fs.readFileSync(hasCache)
        } else {
            return null;
        }
    } catch (error) {
        return null;
    }

}

const deleteFile = function (event, params, { store }) {
    try {

        const { type, fileId, filePath } = params;
        let removePath = ''
        if (type == 'infoCat') {
            removePath = getDocumentsPath() + filePath;
        } else {
            const key = `firCache.${fileId}`;
            const hasCache = store.get(key);
            if (hasCache) {
                removePath = hasCache;
                store.delete(key);
            }
        }
        if (removePath) {
            fs.remove(removePath)
                .then(() => {
                    // console.log('deleteFile success!')
                })
                .catch(err => {
                    console.error(err)
                });
        }


    } catch (error) {
        // console.log('deleteFile error==');
        console.error(error);
    }


}

const createFileLink = function (event, data, { store }) {
    console.log('createFileLink-----------', data)
}


module.exports = {
    saveFile,
    getFile,
    deleteFile,
    createFileLink
}