"""
video.py h265[h264]
"""

import sys
import subprocess as sp
import shlex
import time
import os

DAT_FOLDER = "/extdisk/origin"
TARGET_FOLDER = "/extdisk/camera"
SUFFIX = ".dat"
TARGET_SUFFIX = ".mp4"


def list_folder(org_folder, tar_folder, code):
    current_time = time.strftime(time.strftime("%Y-%m-%d-%H"), time.localtime())
    for root, dirs, files in os.walk(org_folder):
        for f in files:
            if current_time in f:
                print("file ignore: {0} ".format(os.path.join(root, f)))
                continue
            else:
                convert(os.path.join(root, f), os.path.join(tar_folder, code, list(root.split("/"))[-1],
                                                            f.replace(SUFFIX, "") + TARGET_SUFFIX))


def convert(origin, target):
    print("origin: {0} ,target: {1}".format(origin, target))
    cmd = 'ffmpeg -i {0} -c copy {1}'.format(origin, target)
    print("cmd:: {0}".format(cmd))
    args = shlex.split(cmd)
    # status, output = sp.getstatusoutput(cmd)
    # print("status:: {0}, output {1}".format(status, output))
    proc = sp.Popen(args, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    answer = 'Overwrite ? [y/N]'
    try:
        outs, errs = proc.communicate(timeout=300)
        print(outs, errs)
        if answer in outs:
            proc.stdin.write(b'y')
        if proc.returncode == 0:
            print("{0} convert {1} Success, origin dat will remove!".format(origin, target))
            os.remove(origin)
        else:
            print("{0} convert fail".format(origin))
    except sp.TimeoutExpired:
        proc.kill()


if __name__ == "__main__":
    codec = "h265"
    if len(sys.argv) > 1:
        codec = sys.argv[1]
    # timeout=sys.argv[2]
    print("codec:: {0}".format(codec))
    list_folder(DAT_FOLDER, TARGET_FOLDER, codec)
