import os, sys, logging

from services.loft_service import LoftService
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):

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

        service = LoftService(body)
        service.process()

        logging.info('Process complete for %s', service.file_name)


def main():
    logging.info('Starting Solver Service (v1.1.4)...')
    listener = ServiceListener(
        None,
        os.environ['SQS_QUEUE'],
        create_queue=False,
        region_name=os.environ['AWS_REGION'],
        aws_access_key=os.environ['AWS_ACCESS_KEY_ID'],
        aws_secret_key=os.environ['AWS_SECRET_ACCESS_KEY'])
        # endpoint_url=os.environ['ENDPOINT_URL'])
    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()