# -*- coding: utf-8 -*-
import os
from threading import Thread

import cfgtools
from msgbus import (
    FM_PARAM,
    MBEasyContext,
    TK_STORECFG_GET,
    TK_SYS_NAK,
)

import boto3
from helper import (
    config_logger,
    import_pydevd,
)
from mbcontextmessagehandler import (
    MbContextMessageBus,
    MbContextMessageHandler,
)
from messagehandlerbuilder import TopicClientMessageHandlerBuilder
from topicclient import SqsConsumer

REQUIRED_SERVICES = "StoreWideConfig"


def main():
    import_pydevd(os.environ["LOADERCFG"], 9152, False)

    config_logger(os.environ["LOADERCFG"], "TopicClient")
    config_logger(os.environ["LOADERCFG"], "TopicClientReceiveThread")

    mb_context = MBEasyContext("TopicClient")
    message_bus = MbContextMessageBus(mbcontext=mb_context)
    message_handler = MbContextMessageHandler(
        message_bus=message_bus,
        service_name="TopicClient",
        service_type="TopicClient",
        required_services=REQUIRED_SERVICES,
        event_handler_builder=None,
    )

    store_code = _read_sw_config(mb_context, "Store.Id")
    context = _read_sw_config(mb_context, "BackOffice.Host")
    config = cfgtools.read(os.environ["LOADERCFG"])
    server_queue_url = config.find_value("TopicClient.ServerQueueUrl")
    aws_access_key = config.find_value("TopicClient.AwsAccessKey")
    aws_secret_key = config.find_value("TopicClient.AwsSecretKey")
    subjects = config.find_values("TopicClient.ClientSubjects")
    queue_url = config.find_value("TopicClient.QueueUrl")
    region_name = config.find_value("TopicClient.RegionName")
    endpoint_url = config.find_value("TopicClient.EndpointUrl", None)
    message_maximum_length = int(config.find_value("TopicClient.MessageMaximumLength", 250))

    queue = boto3.resource(
        "sqs",
        aws_access_key_id=aws_access_key,
        aws_secret_access_key=aws_secret_key,
        region_name=region_name,
        endpoint_url=endpoint_url
    ).Queue(queue_url + store_code)

    sqs_consumer = SqsConsumer(message_bus, queue, store_code)
    t = Thread(target=sqs_consumer.run)
    t.daemon = True
    t.start()

    for subject in subjects:
        message_bus.subscribe(subject)

    message_handler_builder = TopicClientMessageHandlerBuilder(
        server_queue_url=server_queue_url,
        endpoint_url=endpoint_url,
        region_name=region_name,
        aws_access_key_id=aws_access_key,
        aws_secret_access_key=aws_secret_key,
        subjects=subjects,
        store_code=store_code,
        context=context,
        message_maximum_length=message_maximum_length,
    )
    message_handler.event_handler_builder = message_handler_builder
    return message_handler.handle_events()


def _read_sw_config(mb_context, key):
    reply = mb_context.MB_EasySendMessage("StoreWideConfig", token=TK_STORECFG_GET, format=FM_PARAM, data=key)
    if reply.token == TK_SYS_NAK:
        return None
    return reply.data.decode()
