#!/usr/bin/env python

"""Play subtitles with correct timing to stdout."""

from __future__ import print_function
import logging
from threading import Timer, Lock
import srt_tools.utils
import sys
import time

log = logging.getLogger(__name__)
output_lock = Lock()


def print_sub(sub, encoding):
    log.debug("Timer woke up to print %s", sub.content)

    with output_lock:
        try:
            sys.stdout.write(sub.content + "\n\n")
        except UnicodeEncodeError:  # Python 2 fallback
            sys.stdout.write(sub.content.encode(encoding) + "\n\n")
        sys.stdout.flush()


def schedule(subs, encoding):
    timers = set()
    log.debug("Scheduling subtitles")

    for sub in subs:
        secs = sub.start.total_seconds()
        cur_timer = Timer(secs, print_sub, [sub, encoding])
        cur_timer.name = "%s:%s" % (sub.index, secs)
        cur_timer.daemon = True
        log.debug('Adding "%s" to schedule queue', cur_timer.name)
        timers.add(cur_timer)

    for timer in timers:
        log.debug('Starting timer for "%s"', timer.name)
        timer.start()

    while any(t.is_alive() for t in timers):
        time.sleep(0.5)


def main():
    examples = {"Play a subtitle": "srt play -i foo.srt"}

    args = srt_tools.utils.basic_parser(
        description=__doc__, examples=examples, no_output=True
    ).parse_args()
    logging.basicConfig(level=args.log_level)
    srt_tools.utils.set_basic_args(args)
    schedule(args.input, args.encoding)


if __name__ == "__main__":  # pragma: no cover
    main()
