import argparse
import sys
import webbrowser
import asyncio
from pathlib import Path
import pkg_resources

import logging
logger = logging.getLogger(__name__)

from .project import Project
from .updater import newVersionAvailable, update
from .server import listen, handleConnection

async def run(projectPath: Path, host: str, uploadURL: str):
    logger.info(f'Starting millConnect client {pkg_resources.get_distribution('millconnect').version}.')

    # TODO: add check if application is currently running.
    # TODO: Could intercept with restarting into new application.

    if newVersionAvailable():
        update()

    project = Project(projectPath)

    stop = asyncio.get_running_loop().create_future()

    # create socket for frontend connection
    server = await listen('localhost', 8765, lambda socket: handleConnection(socket, project, host, stop))

    webbrowser.open_new_tab(uploadURL)

    await stop
    server.close()
    await server.wait_closed()

def main():
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s: %(message)s')

    parser = argparse.ArgumentParser(description='millConnect order creator.')
    parser.add_argument('projectPath', type=Path, help='The path to a project folder.')
    parser.add_argument('--host', nargs='?', type=str, default='https://api.connect.millhouse.de/v1', help='The URL of the api.')
    parser.add_argument('--uploadURL', nargs='?', type=str, default='https://connect.millhouse.de/uploadOrder', help='The URL to open in the browser.')

    args = parser.parse_args()
    asyncio.run(run(projectPath=args.projectPath, host=args.host, uploadURL=args.uploadURL))

if __name__ == '__main__':
    main()