# - *- coding: utf- 8 - *-
import telebot
from telebot import types
import requests
import sqlite3
from platform import platform
import re
import time


osx = platform()[0], platform()[1],  platform()[2], platform()[3], platform()[4], platform()[5], platform()[6]

if osx == ('W', 'i', 'n', 'd', 'o', 'w', 's'):
    dr = '\\'
else:
    dr = '/'



Token = '1024025544:AAGmpryOHEz33ZxlZ0yrgTUR0G3TyyLmQss'




bot = telebot.TeleBot(Token)
chat_ids_file = 'chat_ids.txt'
admin = 'admin.txt'


users_amount = [0]

conn = sqlite3.connect("film_id.db")

cursor = conn.cursor()

cursor.execute("""CREATE TABLE IF NOT EXISTS film
                (id integer PRIMARY KEY, title TEXT, file_id TEXT, description TEXT)
            """)
conn.commit()

# ВОТ ТУТ ВОТ НАЧИНАЕТСЯ МОЙ КОД
 # Импортни его в начало
def get_films_dict(film_name):
    with sqlite3.connect("film_id.db") as connection:
        cursor = connection.cursor()
        try:
            cursor.execute(f"""SELECT id, title FROM film WHERE title LIKE '%{film_name}%'""")
            return {film_id[0]: film_id[1] for film_id in cursor.fetchall()}
        except Exception as e:
            return None


def get_films_description(film_id):
    with sqlite3.connect("film_id.db") as connection:
        cursor = connection.cursor()
        cursor.execute(f"""SELECT description FROM film WHERE id = ?""", (film_id, ))
        return cursor.fetchone()[0]


def get_file_id(film_id):
    with sqlite3.connect("film_id.db") as connection:
        cursor = connection.cursor()
        cursor.execute(f"""SELECT file_id FROM film WHERE id = ?""", (film_id, ))
        return cursor.fetchone()[0]


def get_film_markup(film_name):
    films = get_films_dict(film_name)
    if not films:
        return None
    markup = types.InlineKeyboardMarkup()
    for film_id, film_name in films.items():
        button = types.InlineKeyboardButton(
            text=film_name,
            callback_data=f'get_film_{film_id}'
        )
        markup.row(button)
    return markup


@bot.callback_query_handler(func=lambda call: call.data.startswith('get_film_'))
def send_film(call):
    film_id = call.data[9:]
    description = get_films_description(film_id)
    file_id = get_file_id(film_id)
    #file = open(f'{file_id}.mp4', 'rb') #Вот тут путь укажешь до файла с id = film_id
    bot.send_video(
        chat_id=call.from_user.id,
        data=file_id,
        caption=description
    )


def send_film_markup(message):
    markup = get_film_markup(message.text)
    if not markup:
        text = 'Извините, но такого фильма нет'
    else:
        text = 'Выберите фильм: '
    bot.send_message(
        message.from_user.id,
        text,
        reply_markup=markup
    )


# ВОТ ТУТ ОН ЗАКАНЧИВАЕТСЯ



def save_chat_id(chat_id):
    
    chat_id = str(chat_id)
    with open(chat_ids_file,"a+") as ids_file:
        ids_file.seek(0)

        ids_list = [line.split('\n')[0] for line in ids_file]

        if chat_id not in ids_list:
            ids_file.write(chat_id + '\n')
            ids_list.append(chat_id)
            print('New chat_id saved: ' + chat_id)
        else:
            print('chat_id'+ chat_id + 'is already saved')
        users_amount[0] = len(ids_list)
    return


def send_message_users(message):

    def send_message(chat_id):
        data = {
            'chat_id': chat_id,
            'text': message
        }
        
        response = requests.post('https://api.telegram.org/bot'+Token+'/sendMessage', data=data)
        res = str(response.json)
        print(res)
        if res == '<bound method Response.json of <Response [403]>>':                 
            with open(chat_ids_file, "r") as f:
                lines = f.readlines()
            with open(chat_ids_file, "w") as f:
                for line in lines:
                    if line.strip("\n") != chat_id:
                        f.write(line)
        else:
            pass
                        
    with open(chat_ids_file, "r") as ids_file:
        ids_list = [line.split('\n')[0] for line in ids_file]

    [send_message(chat_id) for chat_id in ids_list]



def addFilm(message):
    conn = sqlite3.connect("film_id.db")
    cursor = conn.cursor()
    ############Пример записи в бд 
    caption = open('file'+dr+'caption.txt', encoding = 'utf-8').read()
    name = open('file'+dr+'name.txt', encoding = 'utf-8').read()
    video = open('file'+dr+'video.txt', encoding = 'utf-8').read()
    kino = (name, video, caption)
    cursor.execute("INSERT into film(title,file_id,description) VALUES (?,?,?)", kino)
    conn.commit()
    
    gf = open('file'+dr+'name.txt', mode = 'w', encoding = 'utf-8').write(" ")
    #gf.close()
    df = open('file'+dr+'video.txt', mode = 'w', encoding = 'utf-8').write(" ")
    #df.close()
    pf = open('file'+dr+'caption.txt', mode = 'w', encoding = 'utf-8').write(" ")
    #pf.close()
    bot.send_message(message.chat.id, 'Фильм добавлен')

def names(message):
    try:
        f = open('file'+dr+'name.txt', 'w')
        f.write(message.text)
        fs = open('file'+dr+'film_log.txt', 'a')
        fs.write(time.ctime()+' | '+message.text+'\n')
        fs.close()
        f.close()
        bot.send_message(message.chat.id, 'Теперь отправте фильм')
    except:
        bot.send_message(message.chat.id, 'Произошла ошибка,\nпопробуйте занова')

def caption(message):
    try:
        fg = open('file'+dr+'caption.txt', 'w')
        fg.write(message.text)
        fg.close()
        addFilm(message)
    except:
        bot.send_message(message.chat.id, 'Произошла ошибка,\nпопробуйте занова')

def delFilm(message):
    conn = sqlite3.connect("film_id.db")
    cursor = conn.cursor()
    cursor.execute('DELETE FROM film WHERE title = ?',(str(message.text),))
    conn.commit()
    bot.send_message(message.chat.id, 'Фильм '+str(message.text)+' удалён')


def urledit(message):
    f = open('file'+dr+'url.txt', mode='w', encoding = 'utf-8')
    f.write(str(message.text))
    f.close()
    bot.send_message(message.chat.id, 'Ссылка изменена')

def infoedit(message):
    f = open('file'+dr+'info.txt', mode = 'w', encoding = 'utf-8')
    f.write(str(message.text))
    f.close()
    bot.send_message(message.chat.id, 'Информация обновлена')

def hiedit(message):
    f = open('file'+dr+'hello.txt', mode = 'w', encoding = 'utf-8')
    f.write(str(message.text))
    f.close()
    bot.send_message(message.chat.id, 'Приветствие обновлено')


def redID(message):
    f = open('file'+dr+'id.txt', mode = 'w', encoding = 'utf-8')
    f.write(str(message.text))
    f.close()
    bot.send_message(message.chat.id, "Id канала изменён")


def delladm(message):
    with open('admin.txt', "r") as f:
        lines = f.readlines()
    with open('admin.txt', "w") as f:
        for line in lines:
            if line.strip("\n") != message.text:
                f.write(line)
    bot.send_message(message.chat.id, f"Админ {message.text}  - успешно удален из базы")


def addadm(message):
    try:
        if str(message.text) in open('admim.txt').read():
            bot.send_message(message.chat.id, f"Админ {message.text}  - уже есть в базе")
                                 
        else:
            f = open('admin.txt', 'a')
            f.write(str(message.text) + '\n')
            bot.send_message(message.chat.id, f"Админ {message.text}  - успешно добавлен в  базу",)
                             
    except:
        bot.send_message(message.chat.id, "Ошибка вы ввели не айди юзера")




@bot.message_handler(commands = ['start'])
def start(message):
    chat_id = str(message.chat.id)
    group_id = open('file'+dr+'id.txt')
    idg = group_id.read().replace('\n', '').replace("'", '')

    try:
        some_var = bot.get_chat_member(int(idg), message.chat.id)
        group_id.close()
        user_status = some_var.status
    except:
        pass

    url = open('file'+dr+'url.txt', 'r')

    inl_keyboard = types.InlineKeyboardMarkup()
    s = types.InlineKeyboardButton(text = 'Подписаться', url = url.read())
    inl_keyboard.add(s)

    keyboard = types.ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard = True)
    b = types.KeyboardButton(text = '🔎Поиск')
    d = types.KeyboardButton(text = 'ℹ️Информация')
    keyboard.add(b, d)

    if chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        try:
            f = open('file'+dr+'hello.txt', mode = 'r', encoding = 'utf-8')
            bot.send_message(message.from_user.id, f.read(), reply_markup = keyboard)
            f.close()
            save_chat_id(message.chat.id)
        except:
            bot.send_message(message.chat.id, 'Бот не настроен.', reply_markup = keyboard)

    else:
        try:
            if user_status == 'member' or user_status == 'administrator' or user_status =='creator':
                
                try:
                    f = open('file'+dr+'hello.txt', mode = 'r', encoding = 'utf-8')
                    bot.send_message(message.from_user.id, f.read(), reply_markup = keyboard)
                    f.close()
                    save_chat_id(message.chat.id)
                except:    
                    bot.send_message(message.chat.id, 'Бот не настроен, ждите')

            if user_status == 'restricted' or user_status =='left' or user_status =='kicked':
                bot.send_message(message.chat.id, 'Вы не подписаны на наш канал.\nПодпишитесь на него что бы получить доступ к боту.', reply_markup = inl_keyboard)
        except:
            bot.send_message(message.chat.id, 'Бот не настроен')

@bot.message_handler(commands = ['admin'])
def admin(message):
    chat_id = str(message.chat.id)
    if chat_id in open('admin.txt', 'r').read() or chat_id in open('adm_vip.txt').read():
        global name, caption, video
        name = video = caption = ''
        admin_keyboard = types.ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard = True)
        addFILM = types.KeyboardButton(text = 'Добавить фильм')
        delFILM = types.KeyboardButton(text = 'Удалить фильм')
        dump = types.KeyboardButton(text = 'Список пользователей')
        url = types.KeyboardButton(text = 'Изменить ссылку на канал')
        addADMIN = types.KeyboardButton(text = 'Добавить админа')
        delADMIN = types.KeyboardButton(text = 'Удалить админа')
        redInfo = types.KeyboardButton(text = 'Изменить ℹ️информацию')
        hied = types.KeyboardButton(text = 'Изменить приветствие')
        idC = types.KeyboardButton(text = 'Изменить id канала')
        listA = types.KeyboardButton(text = 'Список админов')
        spam = types.KeyboardButton(text = 'Рассылка')
        back = types.KeyboardButton(text = '⬅️Назад') 
        admin_keyboard.add(addFILM, delFILM, dump, url, addADMIN, delADMIN, redInfo, idC, listA, hied, spam, back)
        bot.send_message(message.from_user.id, "Ты находишься в меню администратора", reply_markup = admin_keyboard)
    else:
        bot.send_message(message.from_user.id, "Ты не админ ¯\_(ツ)_/¯")

@bot.message_handler(content_types = ['video'])
def video_preparing(message):
    global video
    chat_id = str(message.chat.id)
    if chat_id in open('admin.txt').read():
        video = message.video.file_id
        f = open('file'+dr+'video.txt', 'w')
        f.write(video)
        f.close()
        b = bot.send_message(message.chat.id, 'Теперь отправте описание')
        bot.register_next_step_handler(b, caption)

@bot.message_handler(content_types = ['text'])
def caption_preparing(message):
    global name, caption, video
    chat_id = str(message.chat.id)
    text = message.text
    keyboard1 = types.ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard = True)
    b1 = types.KeyboardButton(text = '🔎Поиск')
    d1 = types.KeyboardButton(text = 'ℹ️Информация')
    keyboard1.add(b1, d1)


    if text == 'Добавить фильм' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        a = bot.send_message(message.chat.id, 'Отправте название фильма') 
        bot.register_next_step_handler(a, names)

    elif text == 'Удалить фильм' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        a = bot.send_message(message.chat.id, 'Отправте название фильма который хотите Удалить')
        bot.register_next_step_handler(a, delFilm)

    elif text == 'Список пользователей' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        with open('chat_ids.txt') as f:
            size=sum(1 for _ in f)
        bot.send_message(message.chat.id, 'Количество пользователей: '+ str(size))
        file = open('chat_ids.txt')
        bot.send_document(message.chat.id, file)

    elif text == 'Изменить ссылку на канал' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        url = bot.send_message(message.chat.id, 'Отправте ссылку')
        bot.register_next_step_handler(url, urledit)

    elif text == 'Добавить админа': 
        if chat_id in open('adm_vip.txt').read():
            adda = bot.send_message(message.chat.id, 'Введите id новога админа')
            bot.register_next_step_handler(adda, addadm)
        else:
            bot.send_message(message.chat.id, 'Ты не главный админ')

    elif text == 'Удалить админа':
        if chat_id in open('adm_vip.txt').read():
            della = bot.send_message(message.chat.id, 'Введите id админа которого хотите удалить')
            bot.register_next_step_handler(della, delladm)
        else:
            bot.send_message(message.chat.id, 'Ты не главный админ')

    elif text == 'Список админов':
        if chat_id in open('adm_vip.txt').read():
            f = open('admin.txt')
            bot.send_message(message.chat.id, '<pre>'+f.read()+'</pre>', parse_mode = 'HTML')
        else:
            bot.send_message(message.chat.id, 'Ты не главный админ')

    elif text == 'Изменить ℹ️информацию' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        infored = bot.send_message(message.chat.id, 'Введите текст')
        bot.register_next_step_handler(infored, infoedit)

    elif text == 'Изменить приветствие' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        hi = bot.send_message(message.chat.id, 'Введите текст приветствия')
        bot.register_next_step_handler(hi, hiedit)

    elif text == 'Изменить id канала' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        idr = bot.send_message(message.chat.id, 'Введите новый id')
        bot.register_next_step_handler(idr, redID)

    elif text == 'Рассылка' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        bot.send_message(chat_id, 'Введите сообщение в формате: "РАЗОСЛАТЬ: ваш_текст" без кавычек')

    elif 'РАЗОСЛАТЬ: ' in text and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        msg = text.replace("РАЗОСЛАТЬ: ","")
        bot.send_message(message.chat.id, 'Рассылка начелась')
        send_message_users(msg)
        bot.send_message(message.chat.id, 'Рассылка завершена')

    elif text == '⬅️Назад' and chat_id in open('admin.txt').read() or chat_id in open('adm_vip.txt').read():
        bot.send_message(message.chat.id, 'Выберите действие', reply_markup = keyboard1)

    ##########################################   ТУТ АДМИНКА                 /\№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№
    #########################################################################||#####################################
    group_id = open('file'+dr+'id.txt')
    idg = group_id.read().replace('\n', '').replace("'", '')
    some_var = bot.get_chat_member(int(idg), message.chat.id)
    group_id.close()

    user_status = some_var.status
    url = open('file'+dr+'url.txt', 'r')

    inl_keyboard = types.InlineKeyboardMarkup()
    s = types.InlineKeyboardButton(text = 'Подписаться', url = url.read())
    inl_keyboard.add(s)


    try:
        if user_status == 'member' or user_status == 'administrator' or user_status =='creator':
            if text == '🔎Поиск':
                search = bot.send_message(message.chat.id, 'Введи название фильма')
                bot.register_next_step_handler(search, send_film_markup)

            elif text == 'ℹ️Информация':
                try:
                    info = open('file'+dr+'info.txt', mode = 'r', encoding = 'utf-8')
                    bot.send_message(message.chat.id, info.read())
                except:
                    bot.send_message(message.chat.id, 'Бот не настроен')


        if user_status == 'restricted' or user_status =='left' or user_status =='kicked':
            bot.send_message(message.chat.id, 'Вы не подписаны на наш канал.\nПодпишитесь на него что бы получить доступ к боту.', reply_markup = inl_keyboard)
    except:
        bot.send_message(message.chat.id, 'Бот не настроен')



#if __name__=='__main__':
bot.polling(none_stop = True)