var taskManagerScrapingInterval = null;

TaskManager.container.start = () => {
    $box.getLocal(local => {
        local.status = true;
        $box.setLocal(local, {
            onSet: () => {
                console.log("Opening Google Maps");
                TaskManager.gotoTask(local, 'openMap');
            }
        });
    });
};

TaskManager.container.openMap = () => {
    $box.getLocal(local => {
        console.log(local);


        if (local.taskList.length) {
            local.activeQuery = local.taskList[0];
            local.activeKeyword = local.activeQuery.split('~in~')[0].trim();
            local.activeLocation = local.activeQuery.split('~in~')[1].trim();
            local.activeQuery = local.activeQuery.replace('~in~', ' in ');

            $box.setLocal(local, {
                onSet: () => {
                    console.log("Open Map");
                    console.log(local);
                    chrome.tabs.query({}, (tabs) => {
                        for (let tab of tabs) {
                            if (tab.url && tab.url.includes('google.com/search')) {
                                chrome.tabs.remove(tab.id);
                            }
                        }
                    });

                    // Open Google Maps in a background tab
                    const url = `https://www.google.com/search?tbm=lcl&q=${local.activeQuery}&rflfq=1&num=10&sa=X`;
                    // chrome.tabs.create({ url: url, active: true });
                    chrome.windows.create({ url: url, focused: true });
                }
            });
        } else {
            console.log("Task List is empty");
            local.status = false;
            // $box.setLocal(local);
            TaskManager.gotoTask(local, 'completed');
        }

    });
};


TaskManager.container.completed = () => {
    $box.notify("Scraping Completed");
    $box.getLocal(local => {
        console.log('** Stopping task manager.');
        TaskManager.gotoTask(local, 'stop');
    });
};

TaskManager.container.stop = () => {
    $box.getLocal(local => {
        if (local._taskManager)
            local._taskManager.isWorking = false;
        local.status = false;
        local.openedWindows = [];
        console.log("Stoping Taskmanager");
        console.log(taskManagerScrapingInterval);
        clearInterval(taskManagerScrapingInterval);
        $box.setLocal(local, {
            onSet: () => {
                console.log("Stoping TaskManager");
                console.log(local);
                // closing GoogleMaps tabs
                $box.closeTabIfIncludes('google.com/search');
            }
        });
    });
};