"""
read file with URLs and store in DB
"""
import logging.config
import requests
import yaml
import json
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pathlib import Path
from platformdirs import PlatformDirs
from proton import Message, Event
from proton.handlers import MessagingHandler
from proton.reactor import Container

parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--url', help='link')
parser.add_argument('--video', help='store Url as VideoFile', action="store_true")
parser.add_argument("--api", help="use Kontor API", action="store_true")
parser.add_argument('--config', '-c', default='kontor-docker')
parser.add_argument('--verbose', '-v', action='count', default=0)
args = parser.parse_args()

def get_logger(level: int, config: str):
    dirs = PlatformDirs(config)
    logging_config = Path(dirs.user_config_dir, 'logging-config.yaml')
    with open(logging_config, 'rt') as f:
        configDict = yaml.safe_load(f.read())
    logging.config.dictConfig(configDict)
    logger = logging.getLogger('development')
    if level is not None:
        match level:
            case 0:
                logger.setLevel(logging.INFO)
            case 1:
                logger.setLevel(logging.DEBUG)
            case _:
                logger.setLevel(logging.CRITICAL)
    return logger

class AddLinkMessage(MessagingHandler):
    def __init__(self, server, url, log):
        super(AddLinkMessage, self).__init__()
        log.info("create AddLinkMessage")
        self.server = server
        self.address = "add_link_file"
        self.url = url
        self.log = log

    def on_start(self, event: Event):
        self.log.info("Connection...")
        conn = event.container.connect(self.server, user="artemis", password="artemis")
        event.container.create_sender(conn, self.address)

    def on_connection_error(self, event: Event) -> None:
        self.log.info(f"error: {event}")

    def on_sendable(self, event: Event):
        self.log.info("send message")
        json_content = json.dumps(self.url)
        event.sender.send(Message(body=json_content, address=self.address, content_type="text/json"))
        event.connection.close()
        event.sender.close()

    def on_accepted(self, event: Event) -> None:
        self.log.info(f"accepted: {event}")


if __name__ == '__main__':
    logger = get_logger(args.verbose, args.config)
    logger.info('kontor.add_link started')
    link: str = args.url
    data = {"\"url\"": "\"" + link+ "\""}
    if args.api:
        if args.video:
            request: str = "http://127.0.0.1:8800/api/video/files"
        else:
            request: str = "http://127.0.0.1:8800/api/media/files"
        response = requests.post(request, json=data)
        logger.info(f"Status: {response.status_code}")
        data = response.json()
    else:
        Container(AddLinkMessage("amqp://127.0.0.1:5672", data, logger)).run()
    logger.info('kontor.add_link finished')
