#!/usr/bin/env python
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 pipeline.models import Video

"""
Deliver

Command Line Interface
"""


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):
        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='transcode_stat', 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
        [-i -c -s]
        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'
        )

    args = parser.parse_args()

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

    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()
        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

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


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