import os from 'os';
import dir from 'path';
import fs from 'fs';


export const setWhatsappId = (whatsappId: string, split?: any) => {

    console.log('os.tmpdir(): ', os.tmpdir())

    const whatsappIdFile = dir.join(os.tmpdir(), `whatsappIdInfo.txt`);

    try {

        if (split) {
            fs.unlink(whatsappIdFile, (err) => {

                if (err) {
                    throw err;
                }

                console.log(`Delete File ${whatsappIdFile} successfully.`);
            });
        }

        fs.appendFile(whatsappIdFile, `${whatsappId},`, err => {
            if (err) {
                console.error(err);
            }
            // done!
        });

    } catch (error: any) {

        console.log('There was an error on try to read/delete the whatsappIdInfo.json file: ', error)

    }

}


export const getWhatsappIds = () => {

    const whatsappIdFile = dir.join(os.tmpdir(), `whatsappIdInfo.txt`);

    try {

        if (fs.existsSync(whatsappIdFile)) {

            let whatsappInfo: any = fs.readFileSync(whatsappIdFile, { encoding: 'utf8', flag: 'r' });


            if (whatsappInfo && whatsappInfo.endsWith(',')) {
                whatsappInfo = whatsappInfo.substring(0, whatsappInfo.length - 1);
            }

            whatsappInfo = whatsappInfo.split(',') 

            // console.log('xxxxxxxxxx whatsappInfo: ',whatsappInfo)
 
            return whatsappInfo

        } else {

            console.log('restoreInfo.json file not found!');

        }

    } catch (error) {
        console.log('There was an error on try to read the restoreInfo.json file: ', error)
    }

    return []

}