#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Imports"""
from pyfiglet import Figlet

import os
from photosorganisation.photomulticlassifier import photomulticlassifier
#import matplotlib.pyplot as plt
#import sys
from termcolor import colored
#import photosorganisation
import argparse
#imports from modules
from photosorganisation.photos import get_photos
from photosorganisation.duplicates import find_duplicates, move_duplicates
from photosorganisation.similar_photos import sort_similar, move_similar, difference_score_dict_hem
from photosorganisation.screenshot_classifier import run_screenshot
from photosorganisation.meme_classifier import memes_classifier
from photosorganisation.blurry_classifier import blurry_classifier
import photosorganisation.get_total_size
from photosorganisation.get_total_size import get_size
from photosorganisation.geo_comment_tags import save_tags
from photosorganisation.people_detecting import people
import warnings
warnings.filterwarnings("ignore")
import logging
import os
import tensorflow as tf
import emoji
from mtcnn.mtcnn import MTCNN
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # FATAL
tf.get_logger().setLevel('INFO')
#from tensorflow.python.client import device_lib
tf.get_logger().setLevel(logging.ERROR)
tf.compat.v1.logging.set_verbosity(0)
tf.autograph.set_verbosity(0)
f = Figlet(font='standard')
print(emoji.emojize(colored(f.renderText("       Storage   Heroes     "), "red")))



def parse_args():
    ap = argparse.ArgumentParser(description="Optional arguments for choosing sorting criteria")
    ap.add_argument("-d", "--duplicates",action='store_true', required=False, help="Option to sort only duplicates and similar")
    ap.add_argument("-m", "--memes",action='store_true', required=False, help="Option to sort only memes")
    ap.add_argument("-s", "--screenshots",action='store_true', required=False, help="Option to sort only Screenshots")
    ap.add_argument("-b", "--blurry",action='store_true', required=False, help="Option to sort only blurred photos")
    ap.add_argument("-c", "--classification",action='store_true', required=False, help="Option to just classify and tags photos")
    requiredNamed = ap.add_argument_group('required arguments')
    requiredNamed.add_argument('-f', '--folder_path', help='Input folder path', required=False, default='./')
    return vars(ap.parse_args())

if __name__ == "__main__":

    args = parse_args()
    folder_path = args["folder_path"]


    ###
    total_size = get_size(folder_path)
    received_photos,folders = get_photos(folder_path)
    total_photos = len(received_photos)
    total_folders = len(folders)-1
    print(emoji.emojize(colored(f"Found total {total_photos} :camera_with_flash: photos from {total_folders} sub-folders. :floppy_disk: Total size: {total_size}","blue","on_red",attrs=['bold'])))
    ###
    if args["duplicates"] == True:
        ####run duplicates
        #print(args)
        duplicates,hash_keys = find_duplicates(received_photos)
        print(emoji.emojize(colored(f"Found {len(duplicates)} duplicates :collision: ","red")))
        move_duplicates(duplicates,folder_path)


    if args["screenshots"] == True:
        ### screenshots
        run_screenshot(folder_path)
        total_screenshots_size = get_size(os.path.join(folder_path, 'Screenshots'))
        print(emoji.emojize(colored(f"Found and moved Screenshots to folder; size: {total_screenshots_size} :smiling_face_with_halo:", "green")))


    if args["memes"] == True:
        ### memes
        memes_classifier(folder_path)
        total_memes_size = get_size(os.path.join(folder_path, 'Memes'))
        print(emoji.emojize(colored(f"Found and moved Memes to folder; size: {total_memes_size} :smiling_face_with_halo: ","green")))

    if args["blurry"] == True:
        ### blurry
        blurry_classifier(folder_path)
        total_blurry_size = get_size(os.path.join(folder_path, 'Blurry'))
        print(emoji.emojize(colored(f"Found and moved Blurry photos to folder; size: {total_blurry_size} :smiling_face_with_halo: ","green")))


    if args["duplicates"] == True:
        ### similar
        print(emoji.emojize(colored("Sorting near-duplicates :face_with_monocle: ...","magenta", attrs=['bold'])))
        received_photos2, folders = get_photos(folder_path)
        similar = sort_similar(received_photos2)
        move_similar(similar, folder_path)

    elif args["duplicates"] == False and args["blurry"] == False and \
    args["screenshots"] == False and args["memes"] == False:
        ####run duplicates
        duplicates,hash_keys = find_duplicates(received_photos)
        print(colored(f"Found {len(duplicates)} duplicates","red"))
        move_duplicates(duplicates,folder_path)


        ### screenshots
        run_screenshot(folder_path)
        total_screenshots_size = get_size(os.path.join(folder_path, 'Screenshots'))
        print(emoji.emojize(colored(f"Found and moved Screenshots to folder; size: {total_screenshots_size} :smiling_face_with_halo:", "green")))
        ### memes
        memes_classifier(folder_path)
        total_memes_size = get_size(os.path.join(folder_path, 'Memes'))
        print(emoji.emojize(colored(f"Found and moved Memes to folder; size: {total_memes_size} :smiling_face_with_halo: ","green")))
        ### blurry
        blurry_classifier(folder_path)
        total_blurry_size = get_size(os.path.join(folder_path, 'Blurry'))
        print(emoji.emojize(colored(f"Found and moved Screenshots to folder; size: {total_screenshots_size} :smiling_face_with_halo:", "green")))


        ###similar
        received_photos2, folders = get_photos(folder_path)
        print(emoji.emojize(colored("Sorting near-duplicates photos :face_with_monocle: ...","magenta", attrs=['bold'])))
        similar = sort_similar(received_photos2)
        move_similar(similar, folder_path)

####Classification to move to folders
#if args["classification"] == True:
    detector = MTCNN()
    to_organise_photos, folders = get_photos(folder_path)
    #print(to_organise_photos)
    # 1. first for all the images, add geo tags.
    print(emoji.emojize(colored("Adding Geo Tags :globe_showing_Europe-Africa:...", "blue",attrs=['bold'])))
    for index, filename in enumerate(to_organise_photos):
        if os.path.isfile(filename):
            if filename.lower().endswith(('.png')):
                pass
            else:
                save_tags(filename)
    # 2. Then, mkdir People, run the face detector, move to ppl folder
    #print("Sorting photos with people...")
            people(filename,folder_path,detector)
    print(emoji.emojize(colored("Added places Tags :world_map: :classical_building: :Statue_of_Liberty: to your photos...","green",attrs=['bold'])))
    print(emoji.emojize(colored("Classifiying your photos :red_hair: :dog_face: :shallow_pan_of_food:...","green",attrs=['bold'])))
    photomulticlassifier(folder_path)
print(emoji.emojize(colored(f.renderText("       Done     "), "green")))










# 3. pass the left overs to the multi-classifier, it moves to folders. sorted
# 4.and then may be add tags?
# 5. document neatly with usage and everything
# 6. download a big photos from my cloud may be and into my HD
# 7. use the sorted for statistics? Efficiency, memory in size?
# 8. future better cnn models, ideas, selfies, face recognition
