#!/usr/bin/env python
import os
import sys
import argparse
from VEDA.utils import get_config

project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_path not in sys.path:
    sys.path.append(project_path)


class DeliverCli:
    """
    Deliver

    Command Line Interface
    """

    def __init__(self, **kwargs):
        self.args = None
        self.test = False
        self.logging = kwargs.get('logging', True)

        self.ROOT_DIR = os.path.dirname(os.path.dirname(
            os.path.abspath(__file__)
        ))
        self.celery_daemon = os.path.join(self.ROOT_DIR, 'control', 'celeryapp.py')

    def get_args(self):
        parser = argparse.ArgumentParser()
        parser.usage = '''
        {cmd} -l List
        [-l ]
        Use --help to see all options.
        '''.format(cmd=sys.argv[0])

        parser.add_argument(
            '-l', '--list',
            help='Unused, Exit',
            action='store_true'
            )

        self.args = parser.parse_args()
        self._parse_args()

    def _parse_args(self):
        self.list = self.args.list

    def run(self):
        """
        Launch Celery Delivery Worker

        """
        auth_dict = get_config()

        if auth_dict is not None:
            os.system(
                ' '.join((
                    'python',
                    self.celery_daemon,
                    'worker',
                    '--loglevel=info',
                    '--concurrency=' + str(auth_dict['celery_threads']),
                    '-Q ' + auth_dict['celery_deliver_queue'] + ',' + auth_dict['celery_heal_queue'],
                    '-n deliver.%h'
                ))
            )


def main():
    deliverinstance = DeliverCli()
    deliverinstance.get_args()
    deliverinstance.run()


if __name__ == '__main__':
    sys.exit(main())
