#!/usr/bin/env python3
# -*- coding: utf-8 -*-

""" Author:                     Hendrik Schutter, localhorst@mosad.xyz
    Date of creation:           2022/02/13
    Date of last modification:  2022/01/25
"""

import os
import sys
import time
import subprocess
import datetime

def supported_file_extension(filename):
    if filename.endswith('.mp4') or filename.endswith('.mkv'):
        return True
    return False

def get_length(filename):
    result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
                             "format=duration", "-of",
                             "default=noprint_wrappers=1:nokey=1", filename],
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL)
    try:
        length = float(result.stdout)
    except ValueError:
        length = 0.0
    return length

def get_codec(filename):
    result = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
                             "-show_entries", "stream=codec_name",
                             "-of", "default=noprint_wrappers=1:nokey=1", filename],
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL)
    return str(result.stdout.decode("utf-8")).rstrip("\n")

def get_resolution(filename):
    result = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
                             "-show_entries", "stream=width,height",
                             "-of", "default=noprint_wrappers=1:nokey=1", filename],
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL)
    try:
        resolution = str(result.stdout.decode("utf-8")).rstrip("\n").replace("\n", "x")
    except ValueError:
        resolution = "NaN"
    return resolution

def human_readable_size(size, decimal_places=2):
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']:
        if size < 1024.0 or unit == 'PiB':
            break
        size /= 1024.0
    return f"{size:.{decimal_places}f} {unit}"

def cut_file_name(filename, max_lenght, ellipsis="..."):
    if len(filename) > max_lenght:
        return filename[:max_lenght-len(ellipsis)] + ellipsis
    else:
        return filename

def main() -> None:
    if(len(sys.argv) != 2):
        path = '.'
    else:
        path = sys.argv[1]

    for root, dirs, files in os.walk(path, topdown=False):
        for name in  filter(supported_file_extension, files):
            full_path = os.path.join(root, name)
            print ("{:<64} | {:<8} | {:<16} | {:<8} | {:<8}".format(cut_file_name(name, 64), str(datetime.timedelta(seconds=get_length(full_path))).split(".")[0], human_readable_size(os.path.getsize(full_path)), get_codec(full_path), get_resolution(full_path)))          
            
if __name__ == "__main__":
    main()
