#!/usr/bin/env python
"""
Deliver

Command Line Interface
"""
import os
import sys
import argparse
import datetime
from datetime import timedelta
import pytz

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

from control.celeryapp import maintainer_healer
from control.veda_heal import VedaHeal
from VEDA_OS01.models import Course, Video
from VEDA_OS01.transcripts import retrieve_three_play_translations
from VEDA.utils import get_config


class HealCli:

    def __init__(self, **kwargs):
        self.logging = kwargs.get('logging', True)

        self.binscript = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'heal')

    def schedule(self):
        """
        Reschedule Heal process via Celery ETA
        """
        auth_dict = get_config()
        go_time = datetime.datetime.now(pytz.timezone("America/New_York")) \
                      .replace(hour=0, minute=0, second=0, microsecond=0) \
                      .astimezone(pytz.utc) + timedelta(days=1)

        maintainer_healer.apply_async((self.binscript,), queue=auth_dict['celery_heal_queue'], eta=go_time)


def main():
    """
    Maintenance Daemon + ETA dialer for healing

    """
    parser = argparse.ArgumentParser()
    parser.usage = '''
        {cmd} -i veda_id
        {cmd} -c course_id
        {cmd} -s schedule
        {cmd} --process-translations
        [-i -c -s --process-translations]
        Use --help to see all options.
        '''.format(cmd=sys.argv[0])

    parser.add_argument(
        '-i', '--veda_id', default=None,
        help='VEDA ID'
        )

    parser.add_argument(
        '-c', '--course_id',
        help='Course ID',
        )

    parser.add_argument(
        '-s', '--schedule',
        help='Trigger Scheduler',
        action='store_true'
        )

    parser.add_argument(
        '--process-translations',
        dest='process_translations',
        help='Retrieves completed 3PlayMedia translations for the videos.',
        action='store_true'
    )

    args = parser.parse_args()

    veda_id = args.veda_id
    course_id = args.course_id
    schedule = args.schedule

    process_translations = args.process_translations
    if process_translations:
        # Only kick off a round of retrieving successful
        # translations from 3Play Media
        os.environ['DJANGO_SETTINGS_MODULE'] = 'VEDA.settings.production'
        retrieve_three_play_translations()
        return

    print '%s - %s: %s' % ('Healing', 'VEDA ID', veda_id)
    print '%s - %s: %s' % ('Healing', 'Course', course_id)

    if veda_id is None and course_id is None and schedule is False:
        VH = VedaHeal()
        VH.discovery()
        VH.purge()

        # Kicks off a round of retrieving successful
        # translations from 3Play Media
        retrieve_three_play_translations()

        HC = HealCli()
        HC.schedule()
        return None

    if veda_id is not None:
        VH = VedaHeal(
            video_query=Video.objects.filter(
                edx_id=veda_id.strip()
                )
            )
        VH.send_encodes()
        return None

    if course_id is not None:
        VH = VedaHeal(
            video_query=Video.objects.filter(
                inst_class=Course.objects.filter(
                    institution=course_id[0:3],
                    edx_classid=course_id[3:8]
                    )
                )
            )
        VH.send_encodes()
        return None

    # TODO: Data backup
    # TODO: API key purge

    if schedule is True:
        HC = HealCli()
        HC.schedule()
        return None


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