"""
Module for functions used in Cesar code/decode
"""
#all imports at first
from string import ascii_letters
from os.path import join, isfile
from tools.my_logger import main_logger
import mimetypes
from os import sep

def decode_cesar(file_path: str) -> str:
    """
    function for decoding cesar
    :param file_path:type str, absolute path for the file to decode
    :return: type str, message decoded
    """
    #call the function with the good shift
    try:
        return __transform_cesar(file_path, -13)
    except FileNotFoundError as error:
        main_logger.error(error)
    return ''


def code_cesar(file_path: str) -> str:
    """
    function for coding cesar
    :param file_path:type str, absolute path for the file to decode
    :return:type str, message coded
    """
    # call the function with the good shift
    try:
        return __transform_cesar(file_path, 13)
    except FileNotFoundError as error:
        main_logger.error(error)
    return ''


def __transform_cesar(file_path: str, shift: int) -> str:
    """
    main function for coding/decoding content of a file
    :param file_path:type str, absolute path for the file to decode
    :param shift: type int, the shift to be applied
    :return: type str, message translated
    """
    #first of all, make controls !
    #file exists ?
    if not isfile(file_path):
        #raise exception for example
        raise FileNotFoundError(f"File doesn't exist: {file_path}. Nothing to do.")
    #Good mimetype ?
    tuple_mt = mimetypes.guess_type(file_path.split(sep)[-1])
    if tuple_mt and tuple_mt[0]!='text/plain':
        error:str = f"Bad type: {tuple_mt[0]}.Only text files."
        raise FileNotFoundError(error)
    #ready for treatment !
    #read all content
    main_logger.debug(f"Open file {file_path}")
    with open(file_path, "r", encoding="utf-8") as myfile:
        content: str = myfile.read()
    main_logger.debug("Content read")
    #free file
    #store all characters for the new message in a list
    new_content: list = []
    #make calculation, only one time !
    ascii_size = len(ascii_letters)
    #direct access to methods
    ascii_index = ascii_letters.index
    new_content_append = new_content.append
    for char in content:#for each char
        #need treatment ?
        if char in ascii_letters:
            #yes
            #find original position, add the shift et take the new char
            position: int = ascii_index(char)
            new_position: int = (position + shift) % ascii_size
            new_char: str = ascii_letters[new_position]
            new_content_append(new_char)
        else:
            #no, char stays the same
            new_content_append(char)
    #join all characters from the list
    return "".join(new_content)


if __name__ == "__main__":
    #a simple test in the module definition !
    file_path = join("..","jeux_de_tests", "fichiers_codes", "textes_code.txt")
    print(decode_cesar(file_path))
