import shutil
import os
import random
from _build_list import build_new_list
from _resize import resize_and_copy
from _options_values import copy_mode, output_path, rename_option, rename_values, file_deletion_errors, resize_values


def return_random_name(len_name=20):
    """
    Generate new file name with optional lenght from population

    :param int len_name: Length of generated name
    :return: New generated name
    """

    lang = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
    numbers = "12345678910"

    # limit of population
    if len_name >= 63:
        len_name = 63

    rand_name_lst = random.sample(lang + numbers, len_name)
    return ''.join(map(str, rand_name_lst))


def rename(file_name):
    """
    Creates new names for files according to the selected options:

    :param str file_name: Current file name
    :return: New file name
    """

    if rename_option == 'gen_rand_name':  # gen_rand_name
        return str(
            return_random_name(rename_values['gen_len'])
        )
    elif rename_option == 'phrase_and_rand_name':  # phrase_and_rand_namee
        return str(
            rename_values['phrase'] + return_random_name()
        )
    elif rename_option == 'rand_name_and_phras':  # rand_name_and_phras
        return str(
            return_random_name() + rename_values['phrase']
        )
    elif rename_option == 'phrase_and_origname':  # phrase_and_origname
        return str(
            rename_values['phrase'] + file_name
        )
    elif rename_option == 'origname_and_phrase':  # origname_and_phrase
        return str(
            file_name + rename_values['phrase']
        )
    elif rename_option == 'left_trim':  # left_trim
        new_filename = file_name[rename_values['trim_len']:]
        return new_filename if new_filename else file_name

    elif rename_option == 'right_trim':  # right_trim
        new_filename = file_name[:-rename_values['trim_len']]
        return new_filename if new_filename else file_name


def make_copy(
        wk_list, do_enable, do_resize, do_rename, do_create_subdir
):
    """
    Copying / moving files. Accepts a list of files, options for copying, image processing, renaming.
    When the image processing flag is on, the current file is passed to the resize_and_copy() function,
    where the copying process takes place.

    :param list wk_list: List of files for work
    :param bool do_enable: On/Off function
    :param bool do_resize: On/Off resize
    :param bool do_rename: On/Off rename
    :param bool do_create_subdir: True - orig structure, False - all in one directory
    :return: working result
    """

    # checking for possible errors FIXME допилить механизм проверки путей
    if not do_enable:  # if mode turn ON
        return 'Copying disabled'
    if not wk_list:
        return 'wk_list is empty'

    # if dest folder non exist
    if copy_mode != 'ch_origs' and not os.path.exists(output_path):
        os.mkdir(output_path)

    if copy_mode != 'md_ch_origs':
        for item in wk_list:
            # src path + name + endswith
            one = item['im_path']
            two = item['im_full_name']
            source_file = item['im_path'] + '/' + item['im_full_name']

            out_path = output_path  # output file
            out_name = item['im_name']  # name from wklist

            # new name from rename
            if do_rename:
                out_name = rename(item['im_name'])
            if do_create_subdir:
                out_path = output_path + '/' + item['im_path_sub']  # subdir name from list
                if not os.path.exists(out_path):  # make subdir
                    os.mkdir(out_path)

            # output path + new_name + endswith
            output_file = out_path + '/' + out_name + '.' + item['im_endsw']

            # modify and save passed to funtion resize_and_copy
            if do_resize:
                # if side < than value, then returns 'resize_skiped'
                resize_skipped = resize_and_copy(
                    source_file,
                    output_file,
                    item['im_full_name'],  # file name
                    item['im_width'],  # current image width
                    item['im_height'],  # current image height
                    item['im_format'],  # current image format !!!can change
                )
                # if resize skipped, then can copy without changes
                if resize_skipped == 'resize_skipped' and resize_values['copy_resize_skipped?']:
                    shutil.copy2(source_file, output_file)
            else:  # copy source file to output folder
                shutil.copy2(source_file, output_file)

            if copy_mode == 'md_move':  # if move, removing source file
                os.remove(source_file)
                if os.path.isfile(source_file):
                    file_deletion_errors.append(source_file)

    if file_deletion_errors:  # FIXME
        print('Error deletions:', file_deletion_errors)

    build_new_list(
        output_path, 'Destination Folder', recursive=False, show_source=True
    )
    return 'Copy successful'
