#-*-codi
print("Загрузка библиотек...")

from twx.botapi import TelegramBot, InputFileInfo, InputFile
import pickle
import time
import os


adminId = 50976308


def Token():
	with open("token", "rb") as f:
		result = pickle.load(f)
	return result


bot = TelegramBot(Token())


def SaveOffset():
	global offset
	with open("offset", "wb") as f:
		pickle.dump(offset, f)


def LoadDB(cel):
	if cel == "offset":
		print("Загрузка offset")
	else: 
		print("Загрузка списка пользователей...")
	try:
		with open(cel, "rb") as f:
			result = pickle.load(f)
	except Exception:
		file = open(cel, "wb")
		file.close()
		print("Файл не найден!")
		if cel ==  "offset":
			result = 0
		else:
			result = []
	except pickle.UnpicklingError:
		file = open(cel, "wb")
		file.close()
		print("Ошибка загрузки!")
		if cel == "offset":
			result = 0
		else:
			result = []
	else:
		print("Загрузка прошла успешно!")
	return result


def LoadUserDB(user_id, cel):
	file_name = cel + str(user_id)
	try:
		with open(file_name, "rb") as f:
			result = pickle.load(f)
	except Exception:
		file = open(file_name, "wb") 
		file.close()
		print("Файл не найден!")
		result = [0, 0]
	except pickle.UnpicklingError:
		file = open(file_name, "wb")
		file.close()
		print("Ошибка загрузки!")
		result = [0, 0]
	else:
		print("Загрузка прошла успешно!")
	return result


def NewUserAdd(user_id, cell):
	userlist = LoadDB(cell)
	first_len = len(userlist)
	if len(userlist) == 0:
		userlist.append(user_id)
	elif len(userlist) == 1:
		if userlist[0] != user_id:
			userlist.append(user_id)
	else:
		for i in range(0,1): #не используется по назначению
			for j in range(0,len(userlist)-1):
				if userlist[j] == user_id:
					break
			userlist.append(user_id)
	if first_len != len(userlist):	
		with open(cell, "wb") as f:
			pickle.dump(userlist, f)
		x = True
		print("Добавлен новый пользователь!")
	else: x = False
	return x


def NewUserInfoAdd(user_id, first_name, last_name, username):
	user_info = { "first_name" : first_name, "last_name" : last_name, "username" : username}
	with open("info" + str(user_id), "wb") as f:
		pickle.dump(user_info, f)
	print("Информация о пользователе добавлена")


def UserInfo(user_id):
	print("Загрузка информации пользователя...")
	try:
		with open("info" + str(user_id), "rb") as f:
			user_info = pickle.load(f)
	except Exception:
		print("Информация не найдена!")
		user_info = False
	except pickle.UnpicklingError:
		print("Загрузка информации не возможна!")
		user_info = False
	else:
		("Загрузка прошла успешно!")
	return user_info


def CheckId():
	while True:
		while True:
			user_id_in = input("Введите id: ")
			try:
				user_id = int(user_id_in)
			except Exception:
				print("Ошибка! Попробуй еще раз.")
			else: break
		userlist = LoadDB("users")
		print(userlist)
		if len(userlist) != 0:
			for j in userlist:
				if j == user_id:
					print("Информация найдена. Показать? \n'yes' или 'no'")
					ans = input(">>> ")
					if ans == "yes": 
						user_info = UserInfo(user_id)
						if user_info != False: print(user_info)
					break
		else: print("База данных пуста!")
		print("Выполнить поиск еще раз? \n'yes' или 'no'")
		while True:
			ans2 = input(">>> ")
			if ans2 == "yes":
				break
			elif ans2 == "no":
				break
		if ans2 == "no":
			break


def NewAchUserAdd(do):
	while True:
		user_id_in = input("Введите id: ")
		try:
			user_id = int(user_id_in)
		except Exception:
			print("Ошибка! Попробуй еще раз.")
		else:
			break
			if do == "add":
				NewUserAdd(user_id, "userAchOn")
			if do == "del":
				AchUserDel(user_id)


def AchUserDel(user_id):
	userlist = LoadDB("userAchOn")
	try:
		userlist.remove(user_id)
	except Exception:
		result = "Ошибка! Не было включено!"
	else:
		with open("userAchOn", "wb") as f:
			pickle.dump(userlist, f)
		os.remove("AchMsg" + str(user_id))
		os.remove("AchSim" + str(user_id))
		result = "Отключено!"
	return result


def MsgCheck(): # получение сообщений с сервера
	print("Обновление сообщений...")
	global offset
	updates = bot.get_updates(offset + 1, 13, 0).wait()
	for update in updates:
		offset = update[0]
		user_id = update[1][1][0]
		chat_id = update[1][3][0]
		msg = update[1][7]
		first_name = update[1][1][1]
		last_name = update[1][1][2]
		username = update[1][1][3]
		audio = update[1][8]
		photo = update[1][9]
		sticker = update[1][10]
		video = update[1][11]
		location = update[1][13]
		if audio != None:
			if PreAchievement(user_id, "userAchOn") == True:
				MediaAchievement("audioAch", user_id, chat_id, Name(first_name, last_name))
		elif photo != None:
			if PreAchievement(user_id, "userAchOn") == True:
				MediaAchievement("photoAch", user_id, chat_id, Name(first_name, last_name))
		elif sticker != None:
			if PreAchievement(user_id, "userAchOn") == True:
				MediaAchievement("stickerAch", user_id, chat_id, Name(first_name, last_name))
		elif video != None:
			if PreAchievement(user_id, "userAchOn") == True:
				MediaAchievement("videoAch", user_id, chat_id, Name(first_name, last_name))
		elif location != None:
			if PreAchievement(user_id, "userAchOn") == True:
				MediaAchievement("locationAch", user_id, chat_id, Name(first_name, last_name))
		if msg == "/help": bot.send_message(chat_id, Help("chat"))
		elif msg == "/ach_on": 
			result = NewUserAdd(user_id, "userAchOn")
			if result == True: bot.send_message(chat_id, "Активировано!")
			if result == False: bot.send_message(chat_id, "Ошибка!")
		elif msg == "/ach_off": bot.send_message(chat_id, AchUserDel(user_id))
		elif msg == "/ach_stats": bot.send_message(chat_id, AchUserStats(user_id, "chat", Name(first_name, last_name))
		elif msg == "/my_id": bot.send_message(chat_id, "Твой id: " + str(user_id))
		if chat_id == user_id: #пользователь пишет в личку
			if NewUserAdd(user_id, "users") == True: NewUserInfoAdd(user_id, first_name, last_name, username)
		print_msg = str(user_id) + " | "
		print_msg += Name(first_name, last_name)
		print_msg += " | " 
		if msg != None: 
			print_msg += msg
			if PreAchievement(user_id) == True:
	 	 		Achievement(user_id, msg, chat_id, Name(first_name, last_name))
		print(print_msg)
	print("Сообщения обработаны!")
	SaveOffset()


def AchUserStats(user_id, mode, name):
	if mode == "chat":
		check_res = PreAchievement(user_id)
		if check_res == False:
			result = "Ошибка! Надо активировать!"
		if check_res == True:
			user_msgs = LoadUserDB(user_id, "AchMsg") #число сообщений, последняя ачивка
			user_si = LoadUserDB(user_id, "AchSim") #число символов, последняя ачивка
			audio = LoadUserDB(user_id, "audioAch")
			photo = LoadUserDB(user_id, "photoAch")
			video = LoadUserDB(user_id, "videoAch")
			sticker = LoadUserDB(user_id, "stickerAch")
			location = LoadUserDB(user_id, "locationAch")
			result = ("Отправлено (" + name +"): \n")
			result += ("  " + str(user_msgs[1]) + " сообщений,\n")
			result += ("  " + str(user_si[1]) + " символов,\n")
			result += ("  " + str(audio[1]) + " аудио,\n")
			result += ("  " + str(photo[1]) + " изображений,\n")
			result += ("  " + str(video[1]) + " видео,\n")
			result += ("  " + str(sticker[1] + " стикеров,\n")
			result += ("  " + str(location[1]) + " местоположений.")
	return result


def ShowOffset():
	global offset
	print(offset)


def Help(mode):
	if mode == "console":
		result = """
msgcheck - проверка сообщений
automsgch - проверка сообщений опред. время [сек]
checkid - проверка наличия id в БД
showoffset - показ offset
achion - включение 'ачивок' у пользователя
achioff - отключение 'ачивок у пользователя
achion userlist - список пользователей с включеными 'ачивками'
userlist - список пользователей в БД
exit - выход"""
	if mode == "chat":
		result = """
/help - помощь
/ach_on - включение 'ачивок'
/ach_off - отключение 'ачивок'
/ach_stats - статистика
/my_id - показать id"""
	return result


def UserAchievementSave(user_id, cel, x):
	file_name = cel + str(user_id)
	with open(file_name, "wb") as f:
		pickle.dump(x, f)
	print("Успешно сохранено!")


def PreAchievement(user_id):
	userlist = LoadDB("userAchOn")
	if len(userlist) == 0:
		result = False
	if len(userlist) == 1:
		if userlist[0] == user_id:
			result = True
		else: 
			result = False
	if len(userlist) > 1 :
		result = False
		for j in range(0, len(userlist) - 1):
			if userlist[j] == user_id:
				result = True
				break
	return result


def Name(first_name, last_name):
	name = ""
	if first_name != None:
		name += first_name
	if last_name != None:
		name += " "
		name += last_name
	return name


def Achievement(user_id, msg, chat_id, name):
	user_msgs = LoadUserDB(user_id, "AchMsg") #число сообщений, последняя ачивка
	user_si = LoadUserDB(user_id, "AchSim") #число символов, последняя ачивка
	user_msgs[0] += 1
	user_si[0] += len(msg)
	for j in range(1, 10000): #проверка и отправка ачивок "символов"
		if 1000*j > user_si[1]:
			if 1000*j <= user_si[0]:
				bot.send_message(chat_id, name + " набрал " + str(1000*j) + " символов!")
				user_si[1] = 1000*j
				break
			else: break
	for j in range(1, 2000):
		if 50*j > user_msgs[1]:
			if 50*j <= user_msgs[0]:
				bot.send_message(chat_id, name + " отправил " + str(50*j) + " сообщений!")
				user_msgs[1] = 50*j
				break
			else: break
	UserAchievementSave(user_id, "AchMsg", user_msgs)
	UserAchievementSave(user_id, "AchSim", user_si)


def MediaAchievement(media, user_id, chat_id, name):
	user_stats = LoadUserDB(user_id, media)
	user_stats[0] += 1
	for j in range(1, 10000):
		if 50*j > user_stats[1]:
			if 50*j <= user_stats[0]:
				if media == "audioAch":
					thing = "аудио"
				if media == "photoAch":
					thing = "изображений"
				if media == "stickerAch":
					thing = "стикеров"
				if media == "videoAxh":
					thing = "видео"
				if media == "locationAch":
					thing = "местоположений"
				bot.send_message(chat_id, name + " отправил " + str(50*j) + " " + thing + "!")
				user_stats[1] = 50*j
				break


def AutoMsgCheck(sec):
	start_time = time.clock()
	while True:
		try:
			MsgCheck()
		except Exception:
			print("Ошибка при обновлении!")
		if time.clock() - start_time >= sec:
			print("Обновление закончено!")
			break
		time.sleep(3)


print("Загрузка прошла успешно!")


offset = LoadDB("offset")
while True:
	commInput = input(">>> ")
	if commInput == "msgcheck" : 
		MsgCheck()
	elif commInput == "automsgch" : AutoMsgCheck(int(input("Время в секундах: ")))
	elif commInput == "help" : print(Help("console"))
	elif commInput == "checkid": CheckId()
	elif commInput == "showoffset": ShowOffset()
	elif commInput == "achion": NewAchUserAdd("add")
	elif commInput == "achioff": NewAchUserAdd("del")
	elif commInput == "achion userlist": print(LoadDB("userAchOn"))
	elif commInput == "userlist": print(LoadDB("users"))
	elif commInput == "exit" : break
	else: print("Команда не найдена!")