import pickle
import time
from random import randint
class Dict():
    
    def __init__(self, title=''):
        self.title = title
        self.ditems = dict()
        
    def add_item(self, word):
        a = word.split(':')[0].strip()
        b = [elem.strip() for elem in word.split(':')[1].split(',')]
        d = {a:b}
        self.ditems.update(d)

    def rem(self, word):
        self.ditems.pop(word)
    
    def show_items(self):
        return self.ditems

    def dump(self):
        name = self.title
        if self.title == '':
            name = time.ctime().replace(':','-').replace(' ', '_')
        f = open(name, 'wb')
        pickle.dump(self.ditems, f)
        f.close()
        
    def load_dict(self, file):
        f = open(file, 'rb')
        q = pickle.load(f)
        for j in q.items():
            self.ditems.update({j[0]:j[1]})
        f.close()
        print(' ')
        print("Загружен словарь из " + str(len(self.ditems)) + " элементов.")
        print(' ')
        print('Here we go... ')
        print(' ')

    def learn(self):
        t = 0
        k = 0
        time_test = 0
        my_time = len(self.ditems) * 6
        life = round(len(self.ditems) * 0.3) + 1
        words = [i for i in self.ditems.keys()]
        time.clock()
        while len(words) > 0:
            if k == 0:
                start = round(time.time())
                k+=1
            next_word = words.pop(randint(0, len(words)-1))
            print(next_word)
            answer = input('\ ')
            if answer in self.ditems.get(next_word):
                print('Right!')
                print(' ')
            else:
                print("Wrong")
                print(' ')
                print("Правильные варианты перевода: " + ", ".join(self.ditems.get(next_word)).strip(", "))
                print(' ')
                life -= 1
            t = round(time.time()) - start
            if  t > my_time:
                time_test+=1
                break
            if life <= 0:
                break
        if life > 0 and time_test == 0:
            print("Словарь успешно закрелен.")
            print(' ')
        else:
            print("Вы недостаточно хорошо знаете эти слова. Попробуйте начать заново.")
            print(' ')

#
def new_dict(name):
    new_dict = Dict(name)
    print('Вводите слова и их русский(е) эквивалент(ы) в формате "englishword : русскоеслово, другоеслово" (без кавычек)')
    print(' ')
    print('Чтобы удалить неправильно введённую позицию, введите "DEL" и английское слово')
    print(' ')
    print('Чтобы завершить создание словаря, нажмите на Enter')
    while True:
        word = input('\ ')
        if word == '':
            new_dict.dump()
            break
        if word == 'DEL':
            wrong = input('\ ')
            new_dict.rem(wrong)
            continue
        new_dict.add_item(word)
def open_dict(name):
    other_dict = Dict()
    other_dict.load_dict(name)
    other_dict.learn()
#
while True:
    print('Чтобы создать новый словарь, введите "w".')
    print(' ')
    print('Чтобы открыть уже существующий словарь и начать тренировку, введите "r".')
    print(' ')
    print('Чтобы покинуть программу, введите "q". ')
    print(' ')
    ch = input('\ ')
    if ch != 'w' and ch != 'r' and ch != 'q':
        continue
    elif ch == 'w':
        n = input('Введите имя нового словаря (по умолчанию оно будет сформировано из текущей даты и времени): ')
        new_dict(n)
    elif ch == 'r':
        t = input('Введите название файла словаря: ')
        open_dict(t)
    elif ch == 'q':
        break