"""
Module for class definition
"""
#all imports at first
from random import choice
from os.path import isfile
from os import sep
import mimetypes
from string import ascii_lowercase
from tools.translations import make_translation
class HangManGame:
    """
    Class to manage hangman game
    """
    def __init__(self, file_path: str, tries: int = 5) -> None:
        """
        Constructor: init all vars for a new game
        :param file_path: file contains words, txt format
        :param tries: max tries, type integer; default is 5
        """
        #init all vars
        self.__max_tries = tries
        self.__tries = 0
        self.__file_path = file_path
        self.__history_chars = []
        self.__init_word()

    def __init_word(self):
        """
        function called in constuctor: get all words in file
        :return:
        """
        #control for the file path: raise error if not exists
        if not isfile(self.__file_path):
            raise FileNotFoundError(f"File doesn't exist {self.__file_path}")
        #check mimetype
        file_mt = mimetypes.guess_type(self.__file_path.split(sep)[-1])
        if file_mt and file_mt[0] != 'text/plain':
            error: str = f"Bad type: {file_mt[0]}. Only text files."
            raise FileNotFoundError(error)
        #file is ok
        with open(self.__file_path, "r", encoding="utf-8") as myfile:
            #read all lines, clean each line with rstrip and make a choice
            self.__word = choice([word.rstrip() for word in myfile.readlines()])

    def __display_game(self):
        """
        function dedicated for displaying
        :return:
        """
        #Todo: use id and translation files ;-)
        print(make_translation("hangman","num_tries").format(self.__tries,self.__max_tries))
        print(make_translation("hangman","guess_word").format(''.join(self.__guess)))

    def __get_letter_and_control(self)->str:
        """
        get letter from user and return it, after controle !
        :return:
        """
        letter = ''
        while not letter:
            # Todo: use id and translation files ;-)
            # get one letter
            user_letter = input(make_translation("hangman","write_letter")).lower()
            if user_letter in ascii_lowercase and len(user_letter)==1:
                if user_letter in self.__history_chars:
                    print(make_translation("hangman","already_exists"))
                else:
                    self.__history_chars.append(user_letter)
                    letter = user_letter
            else:
                print(make_translation("hangman","bad_write"))
        return letter


    def start(self):
        """
        function to start the game !
        :return:
        """
        #this var stores the word to be discovered; list is easier to use
        self.__guess = list("-" * len(self.__word))
        #vars for ending the while loop
        found = False
        loose = False
        #let's go !
        while not found and not loose:
            letter = self.__get_letter_and_control()
            #good letter ?
            if letter in self.__word:
                #yes, let's reveal the letter in the guess word
                print(make_translation("hangman","good_guess"))
                for index, letter_in_word in enumerate(self.__word):
                    #for each position
                    if letter_in_word == letter:
                        #replace the char
                        self.__guess[index] = letter
            else:
                #oh, no...
                print(make_translation("hangman","bad_guess"))
                self.__tries += 1
            #help user by displaying information
            self.__display_game()
            #check state for the game
            loose = self.__tries >= self.__max_tries
            found = "-" not in self.__guess
        #game ended: which case ?
        if found:
            print(make_translation("hangman","you_win"))
        else:
            print(make_translation("hangman","you_lose").format(self.__word))
