import os, sys, logging

from lib.application_configs import ApplicationConfigs
from services.form_generation_service import FormGenerationService
from services.ability_estimation_service import AbilityEstimationService
from helpers import aws_helper

from daemonize import Daemonize
from sqspy import Consumer

logging.basicConfig(stream=sys.stdout,
                    level=logging.INFO,
                    format="%(levelname)s %(asctime)s - %(message)s")


class ServiceListener(Consumer):
    # add new services here
    SERVICES = {
        FormGenerationService.ACTION: FormGenerationService,
        AbilityEstimationService.ACTION: AbilityEstimationService
    }

    def handle_message(self, body, attributes, messages_attributes):
        # gather/manage/process data based on the particular needs
        logging.info('Incoming message: %s', body)

        # have to switch to either this or the AbilityEstimationService
        # but depending on if we can add the tagset to the sqs message body
        # we either extract that and then delegate to the appropriate service
        # or get the action tag from the object through the aws helper function
        key = aws_helper.get_key_from_message(body)
        bucket = aws_helper.get_bucket_from_message(body)
        action = aws_helper.get_object_tag(key, bucket, 'action')['Value']

        logging.info(f'Process starting for {action}')

        if action in self.SERVICES:
            service = self.SERVICES[action](body)
            service.process()

            logging.info('Process complete for %s', service.file_name)
        else:
            logging.error(f'action of type {action} does not exist.')

def main():
    logging.info('Starting IRT Service: That Was Rasch (v1.5.0)...')

    # ToDo: Figure out a much better way of doing this.
    # LocalStack wants 'endpoint_url', while prod doesnt :(
    if ApplicationConfigs.local_dev_env:
        listener = ServiceListener(
            None,
            ApplicationConfigs.sqs_queue,
            create_queue=False,
            region_name=ApplicationConfigs.region_name,
            aws_access_key=ApplicationConfigs.aws_access_key_id,
            aws_secret_key=ApplicationConfigs.aws_secret_key,
            endpoint_url=ApplicationConfigs.endpoint_url)
    else:
        listener = ServiceListener(
            None,
            ApplicationConfigs.sqs_queue,
            create_queue=False,
            region_name=ApplicationConfigs.region_name,
            aws_access_key=ApplicationConfigs.aws_access_key_id,
            aws_secret_key=ApplicationConfigs.aws_secret_key)

    listener.listen()


if __name__ == '__main__':
    myname = os.path.basename(sys.argv[0])
    pidfile = '/tmp/%s' % myname
    daemon = Daemonize(app=myname, pid=pidfile, action=main, foreground=True)
    daemon.start()