#!/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/13
"""

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.STDOUT)
    return float(result.stdout)

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.STDOUT)
    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.STDOUT)
    return str(result.stdout.decode("utf-8")).rstrip("\n").replace("\n", "x")

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 main() -> None:
    if(len(sys.argv) != 2):
        path = '.'
    else:
        path = sys.argv[1]

    files = filter(supported_file_extension, os.listdir(path))
    for file in files:
        print ("{:<35} {:<10} {:<5} {:<5} {:<5}".format( file, str(datetime.timedelta(seconds=get_length(file))), human_readable_size(os.path.getsize(file)), get_codec(file), get_resolution(file)))

if __name__ == "__main__":
    main()
