#!/usr/bin/env python
# coding: utf-8

from __future__ import (absolute_import, division, print_function)

from logging import getLogger, StreamHandler, DEBUG
logger = getLogger(__name__)
handler = StreamHandler()
# handler.setLevel(DEBUG)
# logger.setLevel(DEBUG)
logger.addHandler(handler)
logger.propagate = False


from pathlib import Path
from common.imagededuper import ImageDeduper

import sys


img_file_ext = ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.gif', '.GIF']


def is_image(path):
    return path.suffix in img_file_ext


def gen_image_filenames(target_dir, recursive):
    image_filenames = []
    if recursive:
        for path in Path(target_dir).glob('**/*'):
            if is_image(path):
                image_filenames.append(str(path))
    else:
        for path in Path(target_dir).glob('*'):
            if is_image(path):
                image_filenames.append(str(path))
    if len(image_filenames) == 0:
        logger.error("Image not found. To search the directory recursively, add the --recursive option.")
        sys.exit(0)
    return image_filenames


def dedupe_images(args):
    target_dir = args.target_dir
    recursive = args.recursive
    deduper = ImageDeduper(args, gen_image_filenames(target_dir, recursive))
    deduper.dedupe(args)
    delete_candidate = deduper.preserve(args)

    if args.run:
        deduper.delete_images(delete_candidate)
        logger.debug("deleted: {}".format(delete_candidate))
    else:
        logger.debug("dry-run")
        logger.debug("delete_candidate: {}".format(delete_candidate))


def main(argv=sys.argv[1:]):
    import argparse
    parser = argparse.ArgumentParser(
        description="finding and deleting duplicate image files based on perceptual hash")
    parser.add_argument("target_dir", type=str)
    parser.add_argument("hash_method", type=str,
        choices=['ahash', 'phash', 'dhash', 'whash-haar', 'whash-db4'],
        help="""method of perceptual hashing.
            ahash(Average hash) phash(Perceptual hash) dhash(Difference hash)
            whash-haar(Haar wavelet hash) whash-db4(Daubechies wavelet hash)""")
    parser.add_argument("hamming_distance", type=int,
        help="allowable Hamming distances.")
    # parser.add_argument("--preserve_largest", type=str,
    #     choice=['filesize', 'pixelsize'],
    #     help="preserve the larget filesize or pixelsize image from duplicate images")
    parser.add_argument("-r", "--recursive", action="store_true", default=False,
        help="search images recursively from the target directory")
    parser.add_argument("-c", "--imgcat", action="store_true",
        help="display duplicate images for iTerm2")
    parser.add_argument("--ngt", action="store_true",
        help="use NGT for calculating Hamming distance between hash of images")
    parser.add_argument("--log", action="store_true",
        help="output logs of duplicate and delete files")
    parser.add_argument("--size", type=str, default="256x256",
        help="resize image (default=256x256)")
    parser.add_argument("--space", type=int, default=0,
        help="space between images (default=0)")
    parser.add_argument("--space-color", type=str, default='black',
        help="space color between images (default=black)")
    # parser.add_argument("--interpolation", type=str, default="INTER_LINEAR",
    #     help="interpolation methods")
    parser.add_argument("--tile-num", type=int, default=8,
        help="horizontal tile number (default=8)")
    parser.add_argument("--no-keep-aspect", dest="keep_aspect", action="store_false",
        help="do not keep aspect when displaying imagest")
    parser.add_argument("--no-subdir-warning", dest="print_warning", action="store_false",
        help="stop warnings that appear when similar images are in different subdirectories")
    parser.add_argument("--no-cache", dest="cache", action="store_false",
        help="do not create image hash cache")
    parser.add_argument("--dry-run", dest="run", action="store_false",
        help="dry run (do not delete any files)")
    args = parser.parse_args()
    dedupe_images(args)


if __name__ == '__main__':
    main()
