const {_android: android} = require('playwright');
const ExcelUtil = require("./excel/ExcelUtil");
const CommandorPage = require("./workers/CommandorPage");
const {MongoManager, formatDate} = require("./workers/mongo_manager");
const alert = require('alert');

const mongoManager = new MongoManager();

let excelUtil = new ExcelUtil();
let collectionName = formatDate(new Date())

async function filterAlreadyBookedContacts(contactList) {
    let alreadyBookedContacts = await mongoManager.getAllSuccessfulItemsForDay(collectionName);
    let contactsToBook = [];
    contactList.forEach((contact) => {
        if (alreadyBookedContacts.find((bookedContact) => bookedContact.email === contact.mail) === undefined) {
            contactsToBook.push(contact)
        }
    })
    return contactsToBook;
}


// Connect to the device.

async function needToBook(contact, mongoManager) {
    let alreadyBooked = await mongoManager.getAllSuccessfulItemsForDay(collectionName)
    let toReturn = true;
    await alreadyBooked.forEach((bookedItem) => {
            if (bookedItem.email === contact.mail) {
                toReturn = false;
            }
        }
    )
    return toReturn
}

async function startBook(contactPojo, device, selectedStore, audioAnalyse, alertBeep) {
    console.log(`型号: ${device.model()}`);
    console.log(`序列号: ${device.serial()}`);
    if (await needToBook(contactPojo, mongoManager)) {
        let commandor = new CommandorPage(contactPojo, device, mongoManager, selectedStore, audioAnalyse, alertBeep);
        //read contacts form excel
        return await commandor.loadPage();
    } else {
        console.log("do not send request --> skip")
    }
}

async function startWithList(contacts, device, selectedStore, audioAnalyse, alertBeep) {
    await contacts.reduce(async (promise, contactPojo) => {
        // This line will wait for the last async function to finish.
        // The first iteration uses an already resolved Promise
        // so, it will immediately continue.
        await promise;
        const contents = await startBook(contactPojo, device, selectedStore, audioAnalyse, alertBeep);
        console.log(contents);
    }, Promise.resolve());
}

async function startBookWithNumbers(startNumber, endNumber, selectedStore, pathToExcelFile = '/Users/lpan/Desktop/contact_all.xlsx', audioAnalyse = false, alertBeep = false) {
    let allContactList = excelUtil.readContacts(pathToExcelFile);
    let contactList;
    if (endNumber <= allContactList.length) {
        contactList = allContactList.slice(startNumber, endNumber);
    } else {
        contactList = allContactList.slice(startNumber, allContactList.length);
    }
    if (contactList.length === 0) {
        alert("联系人数为0")
        return
    }
    mongoManager.connect().then(r => {
            filterAlreadyBookedContacts(contactList).then(listToBook => {
                console.log("number of contacts to book:" + listToBook.length)
                android.devices().then((devices) => {
                    if (devices.length === 0) {
                        alert("未找到连接的设备");
                        return
                    }
                    let segmentNumber = listToBook.length / devices.length;
                    for (let i = 0; i < devices.length; i++) {
                        startWithList(listToBook.slice(i * segmentNumber, segmentNumber * (i + 1)), devices[i], selectedStore, audioAnalyse, alertBeep);
                    }
                })
            })
        }
    )
}

module.exports = startBookWithNumbers