####
#### video files list Creator: videoFilesListCreator.py
####
#### How to use:
#### python videoFilesListCreator.py Directory_Name_video_data_is_pooled [-hms]
####
####

import os
import sys

#import argparse
import urllib.parse

from moviepy.editor import VideoFileClip

def format_filesize(size):
    # ファイルサイズを3桁毎にカンマを入れてフォーマット
    return f"{size:,.0f}"

def format_duration(duration, use_hms=False):
    if use_hms:
        hours, remainder = divmod(duration, 3600)
        minutes, seconds = divmod(remainder, 60)
        # 時間、分、秒が1桁の場合も空白を含めて2桁で表示
        return f"{int(hours):02d}時間 {int(minutes):02d}分 {int(seconds):02d}秒"
    else:
        #return f"{int(duration)}秒"       ## modified, by hand
        return f"{int(duration):,.0f}秒"

def calculate_total_duration(directory_path, use_hms=False):
    # ディレクトリ内の動画ファイルの一覧を取得
    video_files = [f for f in os.listdir(directory_path) if f.endswith(('.mp4', '.avi', '.webm', '.mkv','.MP4', '.AVI', '.WEBM', '.MKV'))]

    total_duration = 0 # 合計再生時間(秒)

    # 処理したディレクトリの絶対パス
    abs_directory_path         = os.path.abspath(directory_path)
    encoded_abs_directory_path = urllib.parse.quote(abs_directory_path)

    # HTML出力の開始部分
    if use_hms:
        html_output  = f"<html><body><h1>動画ファイル一覧</h1>"
        html_output += f"<p><a href='file:///{encoded_abs_directory_path}'>{abs_directory_path}</a></p>"
        html_output += "<table><tr><th width='160'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"
    else:
        html_output  = f"<html><body><h1>動画ファイル一覧</h1>"
        html_output += f"<p><a href='file:///{encoded_abs_directory_path}'>{abs_directory_path}</a></p>"
        html_output += "<table><tr><th width='130'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"

    # 各動画ファイルの再生時間とファイルサイズを計算し、HTMLに追加
    for video_file in video_files:
        video_path         = os.path.join(directory_path, video_file)
        encoded_video_path = urllib.parse.quote(video_path)
        
        try:
            video_clip = VideoFileClip(video_path)
            duration   = video_clip.duration
            size       = os.path.getsize(video_path) # ファイルサイズ(バイト)
        
            # 個別の再生時間、ファイルサイズをフォーマットしてHTMLの表に追加
            formatted_duration = format_duration(duration, use_hms)
            formatted_size     = format_filesize(size)
            if use_hms:
                html_output += f"<tr><td style='text-align:right; width: 160;'>{formatted_duration}</td><td style='text-align:right; width: 160;'>{formatted_size}バイト</td><td><a href='{encoded_video_path}'>{video_file}</a></td></tr>"
            else:
                html_output += f"<tr><td style='text-align:right; width: 130;'>{formatted_duration}</td><td style='text-align:right; width: 160;'>{formatted_size}バイト</td><td><a href='{encoded_video_path}'>{video_file}</a></td></tr>"
        
            total_duration  += duration
            video_clip.close() # 明示的にクローズ
            
        except Exception as e:
            print(f"エラー: {video_file} を処理中にエラーが発生しました。")
            print(e)

    # 合計再生時間を時間単位に変換
    total_hours   = int(total_duration)          // 3600
    total_minutes = (int(total_duration) % 3600) // 60
    total_seconds = int(total_duration)  % 60

    # 合計再生時間をHTMLに追加
    html_output  += f"</table><h2>合計再生時間: {total_hours:02d} 時間, {total_minutes:02d} 分, {total_seconds:02d} 秒</h2></body></html>"

    # 出力ファイル名を生成
    base_directory_name = os.path.basename(directory_path)
    output_filename     = f"video_list_{base_directory_name}.html"

    # 結果を生成された出力ファイルに保存
    with open(output_filename, "wb") as html_file:
        html_output_bytes = html_output.encode("utf-8")
        html_file.write(html_output_bytes)

if __name__ == "__main__":
    # コマンドライン引数からディレクトリパスを取得
    if len(sys.argv) >= 2:
        directory_path = sys.argv[1]
        use_hms = "-hms" in sys.argv # -hms オプションが指定されたら True にする
    else:
        print("使用法: python script.py ディレクトリパス [-hms]")
        sys.exit(1)

    calculate_total_duration(directory_path, use_hms)