const {app, BrowserWindow, ipcMain} = require('electron')
const {_android: android} = require('playwright');
const {startBookWithNumbers, scheduleBookWithNumbers} = require('./src/appointment')
const path = require("path");
const homedir = require('os').homedir();
const loadIniFile = require('read-ini-file')
const configFilePath = path.join(homedir, 'config.ini')
const {exec} = require("child_process");

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 500,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    });

    win.loadFile('index.html').then((r) => {

    })
    ipcMain.on('start-book', (event, startNumber, endNumber, selectedStore, audioAnalyse, alertBeep) => {
        startBook(startNumber, endNumber, selectedStore, audioAnalyse, alertBeep)
    })
    ipcMain.on('schedule-book', (event, startNumber, endNumber, selectedStore, audioAnalyse, alertBeep) => {
        scheduleBook(startNumber, endNumber, selectedStore, audioAnalyse, alertBeep)
    })
    ipcMain.on('clearAllBrowsers', (event) => {
        clearAllBrowsers()
    })
    ipcMain.handle('scan-devices', scanDevices)
    // win.webContents.openDevTools();
}

app.whenReady().then(() => {
    createWindow();
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

function clearAllBrowsers() {
    //detect os
    if (process.platform === 'win32') {
        exec("clear_data.bat", (error, stdout, stderr) => {
            if (error) {
                console.log(`error: ${error.message}`);
                return;
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
                return;
            }
            console.log(`stdout: ${stdout}`);
        });
    } else

        exec(" sh clear_data.sh", (error, stdout, stderr) => {
            if (error) {
                console.log(`error: ${error.message}`);
                return;
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
                return;
            }
            console.log(`stdout: ${stdout}`);
        });
}

function startBook(startNumber, endNumber, selectedStore, audioAnalyse, alertBeep) {
    console.log("startNumber: " + startNumber);
    console.log("endNumber: " + endNumber);
    console.log("selectedStore: " + selectedStore);
    console.log("audioAnalyse: " + audioAnalyse);
    //load config.ini file
    let config = loadIniFile.sync(configFilePath);
    console.log(config);
    let contactExcelFilePath = config.DEFAULT.contact_list_file;
    startBookWithNumbers(startNumber, endNumber, selectedStore, contactExcelFilePath, audioAnalyse, alertBeep).then(() => {
        console.log("stop")
    })
}

function scheduleBook(startNumber, endNumber, selectedStore, audioAnalyse, alertBeep) {
    console.log("scheduleBook: " + startNumber);
    console.log("endNumber: " + endNumber);
    console.log("selectedStore: " + selectedStore);
    console.log("audioAnalyse: " + audioAnalyse);
    //load config.ini file
    let config = loadIniFile.sync(configFilePath);
    console.log(config);
    let contactExcelFilePath = config.DEFAULT.contact_list_file;
    scheduleBookWithNumbers(startNumber, endNumber, selectedStore, contactExcelFilePath, audioAnalyse, alertBeep).then(() => {
        console.log("stop")
    })
}

async function scanDevices() {
    exec("adb devices ", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });
    let deviceList = await android.devices()
    return deviceList.map((item) => {
        return [item.model(), item.serial()]
    })
}



