import asyncio, aiofiles
from asyncio.log import logger
from asyncore import loop
import logging
import os
from datetime import datetime
import recordTasks

# Open the config file and make it accessible via "cfg"
import json
with open("config.json", "r") as file:
    cfg = json.load(file)

l = logging.getLogger(__name__)

useRadarServer = cfg["useRadarServer"]

async def createTemp():
    """ Used on a first time run, creates necessary files & directories for the message encoder to work properly. """
    if not (os.path.exists('./.temp')):
        l.info("Creating necessary directories & files..")
        os.mkdir('./.temp')
        
        # Used for the record generator
        os.mkdir('./.temp/tiles/')
        os.mkdir('./.temp/tiles/output/')

        # Used for radar server downloads
        os.mkdir('./.temp/output')
        os.mkdir('./.temp/output/radarmosaic')
        os.mkdir('./.temp/output/satrad')

        # Create msgId file for bit.py
        async with aiofiles.open('./.temp/msgId.txt', 'w') as msgId:
            await msgId.write('694203')
            await msgId.close()
    else:
        l.debug(".temp file exists")
        return


async def main():
    await createTemp()

    if useRadarServer:
        mosaicTask = asyncio.create_task(recordTasks.updateMosaicTask())
        satradTask = asyncio.create_task(recordTasks.updateSatradTask())

    alertsTask = asyncio.create_task(recordTasks.alertsTask())
    coTask = asyncio.create_task(recordTasks.coTask())
    hfTask = asyncio.create_task(recordTasks.hfTask())
    dfTask = asyncio.create_task(recordTasks.dfTask())
    aqTask = asyncio.create_task(recordTasks.aqTask())
    aptTask = asyncio.create_task(recordTasks.aptTask())
    apTask = asyncio.create_task(recordTasks.apTask())
    brTask = asyncio.create_task(recordTasks.brTask())
    hcTask = asyncio.create_task(recordTasks.hcTask())
    maTask = asyncio.create_task(recordTasks.maTask())
    pTask = asyncio.create_task(recordTasks.pTask())
    tTask = asyncio.create_task(recordTasks.tTask())
    wnTask = asyncio.create_task(recordTasks.wnTask())

    # In theory, these should all run concurrently without problems
    await alertsTask
    await coTask
    await hfTask
    await dfTask
    await aqTask
    await aptTask
    await apTask
    await brTask
    await hcTask
    await maTask
    await pTask
    await tTask
    await wnTask

    if useRadarServer:
        await mosaicTask
        await satradTask

if __name__ == "__main__":
    asyncio.run(main())
