import os
import sys
import time
import tarfile
import tempfile
from datetime import datetime

from path import path

from mbhlib import sh
from mbhlib.daemonize import daemonize

__all__ = [
    'cap_main',
    'annotate_main',
]


HOME = path(os.environ['HOME'])

TT = HOME/'.local/timetracking'
DAEMON_PIDFILE = TT/'daemon.pid'
NOW = datetime.now()
TODAY_DIR = TT/NOW.strftime('%Y-%m-%d')
NOTES = TODAY_DIR/'notes.log'
SCROT_CMD = "scrot -q %(quality)s %(target)s"
NOTE_ENTRY = '%s | %s\n'
LOG = TT/'daemon.log'
DEFAULT_INTERVAL = 30
DEFAULT_QUALITY = 10
RESIZE_PCT = 1024
# MENCODER_CMD = 'mencoder mf://@%(manifest)s -mf h=800:h=600:fps=%(fps)s:type=jpg ' \
#                '-ovc copy -oac copy -o %(output_file)s'
MENCODER_CMD = \
    'mencoder mf://@%(manifest)s -mf w=800:h=600:fps=%(fps)s:type=jpg ' \
    '-ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o %(output_file)s'


# MOGRIFY_CMD = 'mogrify -resize %(resize_pct)s%% ' \
#               '-format %(out_format)s %(target)s'
OUTPUT_NAME = 'today.avi'


def cap_main(quality=DEFAULT_QUALITY):
    mk_and_cd_tt()

    target = _get_now_jpg()
    scrot_cmd = SCROT_CMD % dict(quality=quality, target=target)
    sh(scrot_cmd)
    return 0


def continuous_cap_main_daemon(interval=DEFAULT_INTERVAL):
    pidfile = DAEMON_PIDFILE

    if 'stop' in sys.argv and pidfile.isfile():
        pid = int(pidfile.bytes())
        os.kill(pid, 9)
        pidfile.remove()
        print("killed daemon with pid=%d" % pid)
        return 0

    daemonize(stdout=LOG, stderr=LOG, pidfile=DAEMON_PIDFILE)
    LOG.write_bytes('\ndaemon started at %s\n' % NOW.now(), append=True)

    while True:
        try:
            cap_main()
            LOG.write_bytes('.', append=True)
            time.sleep(interval)
        except KeyboardInterrupt:
            LOG.write_bytes('^C!!!\n', append=True)
            break

    return 0


def annotate_main():
    mk_and_cd_tt()
    msg = NOTE_ENTRY % (NOW.strftime('%H.%M.%S'), ' '.join(sys.argv[1:]))
    NOTES.write_bytes(msg, append=True)
    return 0


def moviefy_main():
    if not TODAY_DIR.files('*.jpg'):
        raise ValueError('nothing in %s to movie-fy' % TODAY_DIR)

    tmpdir = path(_tmp_copy(TODAY_DIR))
#     _mogrify_all_in_dir(tmpdir)
    manifest = _get_and_write_jpg_manifest(tmpdir)
    output = path(tmpdir)/OUTPUT_NAME
    enc_out = _mencode_from_manifest(manifest, output)
    output.copy(TODAY_DIR)

#     tmpdir.rmtree()
    return 0


def peek_main():
    sh('eog %s' % TODAY_DIR)
    return 0


def archive_main():
    raise NotImplementedError


def mk_and_cd_tt():
    if not TODAY_DIR.isdir():
        TODAY_DIR.makedirs()
    os.chdir(TODAY_DIR)


def _get_now_jpg():
    return NOW.now().strftime('%H.%M.%S.jpg')


def _tmp_copy(directory):
    directory = path(directory)
    tmpdir = tempfile.mkdtemp('-' + __name__)

    for jpg_file in directory.files('*.jpg'):
        jpg_file.copy(tmpdir)

    notes = directory/'notes.log'
    if notes.isfile():
        notes.copy(tmpdir)

    return tmpdir


# def _mogrify_all_in_dir(directory, scale_width=RESIZE_PCT):
#     out = ''
#     all_jpgs = path(directory).files('*.jpg')

#     cmd = MOGRIFY_CMD % dict(width=scale_width, target=' '.join(all_jpgs))
#     out += sh(cmd, True)
#     return out


def _get_and_write_jpg_manifest(directory):
    manifest = path(directory)/'manifest.txt'
    manifest_list = list(sorted(path(directory).files('*.jpg')))
    manifest.write_lines(manifest_list)
    return manifest


def _mencode_from_manifest(manifest, output, fps=5):
    cmd = MENCODER_CMD % dict(manifest=manifest, fps=fps, output_file=output)
    out = sh(cmd, True)
    return out


def _archive_dir(directory):
    directory = path(directory).abspath()
    os.chdir(directory.parent)
    target = '%s.tar.bz2' % directory.basename()

    output = tarfile.open(target, 'w:bz2')

    try:
        output.add(directory.basename())
        directory.rmtree()
    except Exception:
        if target.exists():
            target.remove()
        raise


# vim:filetype=python
