import os
from posixpath import ismount
import sys
import time
import subprocess
import datetime
import shutil
import json
import getopt

#_SOURCE_DIR = "/media/nas/nas-photo/imported/"
_SOURCE_DIR = "/share/Photo/imported/"
_DEV = "gopro9_1"
_DAY_DIR = "2022-08-04 - Bukovec-Jano"
_FULL_PATH = _SOURCE_DIR + "/" + _DEV + "/" + _DAY_DIR

try:
    opts, args = getopt.getopt(sys.argv[1:], "hbl:o:s:t:", ["command=", "help", "output=", "backup"])
except getopt.GetoptError as err:
    # print help information and exit:
    print(str(err))  # will print something like "option -a not recognized"
    #usage()
    sys.exit(2)
output = None
# QJ : getopts

for o, a in opts:
    if o == "-h":
        _ACTION = True
    elif o in ("-b", "--backup"):
        _BACKUP = True
    elif o in ("-l", "--level"):
        _LOG_LEVEL = a.upper()
    elif o in ("-o", "--output"):
        OUTPUT_FILE = a
    elif o in ("-s", "--schema"):
        SCHEMA = a
    elif o in ("-t", "--tables"):
        TABLES = a

    else:
        _WIZZARD = True
        
        
video_seq = {}
if os.path.exists(_FULL_PATH):
    for filename in os.listdir(_FULL_PATH):
        if filename.endswith(".MP4"):
            part = "GH" + filename[2:4]
            seq = filename[4:8]
            if not seq in video_seq:
                video_seq[seq] = []
            video_seq[seq].append(part + seq + ".MP4")
            print(filename)
            print(seq)
            print(part)
    print(json.dumps(video_seq,indent=2))
    
    for vid in video_seq:
        export_name = "joined_"  + vid + ".MP4"
        parts = video_seq[vid]
        parts.sort()
        if len(parts) > 1:
            print("This need to be joined!")
            # for p in parts:
            #     join_string =
        else:
            continue
        print(parts)
        
        join_s = "|".join(parts)
        print(join_s)
        # print(type(parts))
        #ffmpeg -i concat:"input1.mp4|input2.mp4" output.mp4
        
        os.chdir(_FULL_PATH)
        
        myCmd = 'ffmpeg -i concat:"' + join_s + '" ' + export_name
        print(myCmd)
        status, output = subprocess.getstatusoutput(myCmd)
        print(output)