import argparse
import os.path
import pathlib
from app.watermark import watermark_text_bottom_right

_FONTS_DIR = pathlib.Path(__file__).parent / "fonts"
_DEFAULT_FONT = str(_FONTS_DIR / "Roboto-Regular.ttf")


def _find_all_files(folder: str, mask: str) -> list:
    root = pathlib.Path(folder)
    return [f"{os.path.join(file.parent, file.name)}" for file in root.rglob(mask, case_sensitive=False) if '_wm' != os.path.splitext(file.name)[0][-3:]]


def _build_output_filename(filename: str) -> str:
    file = pathlib.Path(filename)
    basename, extension = os.path.splitext(file.name)
    newfilename = f"{basename}_wm{extension}"
    print(f"file={file}, basename={basename}, extension={extension}, newname={newfilename}")
    return f"{os.path.join(file.parent, newfilename)}"


def main():
    parser = argparse.ArgumentParser("watermark")
    parser.add_argument("-f", "--font", required=False, default=_DEFAULT_FONT, help='TTF Font file (default: bundled Roboto-Regular)')
    parser.add_argument("-t", "--text", required=True, help='Text watermark')
    parser.add_argument("-i", "--input_filename", required=False, help='Input filename')
    parser.add_argument("-if", "--input_folder", required=False, default=".", help='Input folder (default: current directory)')
    parser.add_argument("-m", "--file_mask", required=False, default="*.jpg", help='File mask (default: *.jpg)')
    parser.add_argument("-o", "--output_filename", required=False, help='Output filename')
    args = parser.parse_args()

    if args.input_filename is not None:
        watermark_text_bottom_right(
            input_image_path=args.input_filename,
            output_image_path=args.output_filename,
            text=args.text,
            font_path=args.font,
            pos=(1000, 200),
            size=60)
    else:
        files = _find_all_files(args.input_folder, args.file_mask)
        print(f"files={files}")
        for file in files:
            newfilename = _build_output_filename(file)
            if os.path.isfile(newfilename):
                continue
            watermark_text_bottom_right(
                input_image_path=file,
                output_image_path=newfilename,
                text=args.text,
                font_path=args.font,
                pos=(1000, 200),
                size=60)
