import argparse
import asyncio
import os

from clarabot_nano.common.config.constants import CommonConfigConstants
from clarabot_nano.common.spawn.constants import ShortNames
from clarabot_nano.development.spawn.common import write_spawn_debug_info
from clarabot_nano.indexer.process import IndexerProcess
from clarabot_nano.indexer.scheduler import IndexingSchedulerEngine
from clarabot_nano.utility.path.resolve import resolve_path


class _TestingIndexingSchedulerEngine(IndexingSchedulerEngine):
    def __init__(self, skip_poll, skip_observe, *args):
        IndexingSchedulerEngine.__init__(self, *args)
        self.__skip_poll = skip_poll
        self.__skip_observe = skip_observe

    async def _poll_sync_traverse(self, *args):
        if self.__skip_poll:
            while True:
                await asyncio.sleep(5)
        await IndexingSchedulerEngine._poll_sync_traverse(self, *args)

    async def _observe_drives(self, *args):
        if self.__skip_observe:
            while True:
                await asyncio.sleep(5)
        await IndexingSchedulerEngine._observe_drives(self, *args)


class _TestingIndexerProcess(IndexerProcess):
    def __init__(self, skip_poll, skip_observe):
        self.skip_poll = skip_poll
        self.skip_observe = skip_observe
        IndexerProcess.__init__(self)

    def _create_scheduler(self, *args):
        return _TestingIndexingSchedulerEngine(
            self.skip_poll,
            self.skip_observe,
            *args,
            self._event_queue,
            self._set_status,
            self._notify_work,
        )


async def startup(skip_poll, skip_observe):
    proc = _TestingIndexerProcess(skip_poll, skip_observe)
    config_dir = resolve_path(proc.get_config()["local"]["config_dir"], strict=True)
    write_spawn_debug_info(config_dir, os.getpid(), ShortNames.INDEXER)
    await proc.run()


def main():
    CommonConfigConstants.DEVELOPMENT = True
    parser = argparse.ArgumentParser("Clarabot Nano - Test Indexer process")
    parser.add_argument("--skip_poll", action="store_true")
    parser.add_argument("--skip_observe", action="store_true")
    args = parser.parse_args()
    asyncio.run(startup(args.skip_poll, args.skip_observe))


if __name__ == "__main__":
    main()
