import telebot
import time
import os
import sys
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from types import *
import requests
from db import Database
# from PIL import Image, ImageFont, ImageDraw
from flask import Flask, render_template, json, request
# from flaskext.mysql import MySQL
import config as cfg

# if message.forward_date != None: Определяет, является ли сообщение пересланым

# from moviepy.editor import VideoFileClip, ImageClip, CompositeVideoClip
# from subprocess import Popen, PIPE
# import markups as nav
# import dictionary as en_ru
# from PIL import Image  #, ImageFont, ImageDraw
# from io import BytesIO
# bio = BytesIO()


app = Flask(__name__)

bot = telebot.TeleBot(cfg.TOKEN)
db = Database('database.db')

# bot.set_my_commands([telebot.types.BotCommand("/start", "На стартовую"),
#                      telebot.types.BotCommand("/help", "Помощь"),
#                      telebot.types.BotCommand("/newlogo", "Создать водяной знак"),
#                      telebot.types.BotCommand("/editlogo", "Редактировать водяной знак"),
#                      telebot.types.BotCommand("/applylogo", "Нанести водяной знак"),
#                      telebot.types.BotCommand("/setposition", "Изменить расположение"),
#                      telebot.types.BotCommand("/setopacity", "Изменить непрозрачность"),
#                      telebot.types.BotCommand("/setscale", "Изменить размер"),
#                      telebot.types.BotCommand("/setangle", "Изменить угол поворота"),
#                      telebot.types.BotCommand("/setlogopic", "Изменить фото водяного знака")
#                      ])

CONTENT_TYPES = ["text", "audio", "document", "photo", "sticker", "video", "video_note", "voice", "location", "contact",
                 "new_chat_members", "left_chat_member", "new_chat_title", "new_chat_photo", "delete_chat_photo",
                 "group_chat_created", "supergroup_chat_created", "channel_chat_created", "migrate_to_chat_id",
                 "migrate_from_chat_id", "pinned_message"]

BLANK_PICTURE = 'sources/blank.png'
START_PICTURE = 'sources/step-1.jpg'
CMD_LIST_PICTURE = BLANK_PICTURE
HOW_WORKS_PICTURE = 'sources/background.jpeg'
APPLY_PICTURE = 'sources/demo-1.gif'
NO_WATERMARK = 'sources/no-watermark.png'
PI = 3.1415926
file_list = list()
language = 'ru'
main_message = ''
some_more = False
# logo_type = ''
logo_path = ''
logo_pos = ''
logo_size = None
logo_opacity = None
logo_angle = None
logo_arrow = None
logo_ext = ''
edit_flag = False
test_flag = False
new_flag = False
saved_flag = False
from_size = False
from_opacity = False
from_rotation = False
user_id = ''


btn_caption = {
    "ru": {
        "reg_bt": "Регистрация",
        "save_bt": "Сохранить",
        "cancel_all_bt": "Очистить",
        "change_rotation_bt": "Изменить угол поворота",
        "go_test_bt": "Перейти к тесту",
        "change_opacity_bt": "Изменить непрозрачность",
        "change_size_bt": "Изменить размер",
        "change_pos_bt": "Изменить расположение",
        "other_file_bt": "Загрузить другой файл",
        "step_back_bt": "Шаг назад",
        "choose_type_bt": "Выбрать другой тип файла",
        "no_bt": "Отмена",
        "come_back_bt": "На стартовую",
        "new_logo_bt": "Создать новый",
        "edit_logo_bt": "Редактировать",
        "apply_logo_bt": "Нанести водяной знак",
        "del_logo_bt": "Удалить водяной знак",
        "text_type_bt": "Текст",
        "photo_type_bt": "Фото",
        "video_type_bt": "Видео",
        "gif_type_bt": "Анимация",
        "how_it_works_bt": "Как это работает",
        "cmd_list_bt": "Список команд"
    },
    "en": {
        "reg_bt": "Sign Up",
        "save_bt": "Save",
        "cancel_all_bt": "Clear",
        "change_rotation_bt": "Change rotation angle",
        "go_test_bt": "Go to test",
        "change_opacity_bt": "Change opacity",
        "change_size_bt": "Change size",
        "change_pos_bt": "Change position",
        "other_file_bt": "Upload another file",
        "step_back_bt": "Step back",
        "choose_type_bt": "Choose a different file type",
        "no_bt": "Саncеl",
        "come_back_bt": "Home",
        "new_logo_bt": "Create new",
        "edit_logo_bt": "Edit watermark",
        "apply_logo_bt": "Apply watermark",
        "del_logo_bt": "Delete watermark",
        "text_type_bt": "Text",
        "photo_type_bt": "Photo",
        "video_type_bt": "Video",
        "gif_type_bt": "Animation",
        "how_it_works_bt": "How it works.",
        "cmd_list_bt": "Command list"
    }}

strings = {
    "ru": {
        "no_watermark": "У вас нет загруженного водяного знака.",
        "save_success_msg": "Ваш водяной знак готов к использованию.\n\n\
Для теста отправьте мне какую-нибудь картинку, чтобы посмотреть, соответсвуют ли настройки вашим ожиданиям.\n\
Вы всегда можете изменить настройки из «Списка команд».",
        "del_msg": "Ваш водяной знак будет удален",
        "setting_completed_msg": "Настройка завершена.",
        "rotation_select_msg": "Укажите угол поворота водяного знака.\n\nМожно указать 0, а сам рисунок подготовить в графическом редакторе с поворотом.",
        "opacity_select_msg": "Укажите степень прозрачности водяного знака.\n\n\t0% - непрозрачный\n\t100% - невидимый",
        "size_select_msg": "Укажите размер относительно ширины основного изображения.",
        "pos_select_msg": "Укажите расположение водяного знака.",
        "under_dev_msg": "<b>В СТАДИИ РАЗРАБОТКИ</b>",
        "are_you_shure_msg": "Вы действительно хотите удалить водяной знак?",
        "send_watermark_msg": "Отправьте мне свой водяной знак.\n\
&#10071;<b>ОБРАТИТЕ ВНИМАНИЕ</b>, если ваш водяной знак имеет прозрачный фон, то его следует отправлять, как «Файл»,\nа не как «Фото или видео».\n\
В противном случае, фон будет заполнен белым или черным цветом.",
        "invalid_type_msg": "Недопустимый тип файла.",
        "bad_command_msg": "Команда не распознана.",
        "quick_logo_msg": "Чтобы быстро нанести водяной знак на фото или видео, прикрепите к сообщению сразу два вложения, как «Фото или видео», а не как «Файл». Первое - основное, второе - водяной знак.\n<b>В СТАДИИ РАЗРАБОТКИ</b>",
        "welcome_msg": "Добро пожаловать",
        "cmd_list_msg": "Я могу помочь вам создать и управлять вашим водяным знаком.\n\nВы можете управлять мной, отправив следующие команды:\n\n\
            /newlogo - создать новый водяной знак\n\
            /editlogo - редактировать водяной знак\n\
            /applylogo - нанести водяной знак\n\n\
Редактировать водяной знак:\n\
            /setposition - изменить расположение\n\
            /setscale - изменить размер\n\
            /setopacity - изменить прозрачность\n\
            /setangle - изменить угол поворота\n\
            /setlogopic - изменить фото водяного знака\n\
            /delelogo - удалить водяной знак",
        "how_work_msg": "Отправьте мне ваш водяной знак, который вы хотите протестировать, написав в тексте сообщения /test\n\n\
Изображение будет размещено на тестовой картинке.\n\
Качество вставленного водяного знака зависит от разрешения фонового изображения. В тесте используется фон с разрешением 1024х683 пикселя.\n\
&#10071;<b>ОБРАТИТЕ ВНИМАНИЕ</b>, если ваш водяной знак имеет прозрачный фон, то его следует отправлять, как «Файл»,\nа не как «Фото или видео».\n\
В противном случае, фон будет заполнен белым цветом, а при повороте появятся черные треугольники.\n\n\
Параметры вставки по умолчанию:\n\
\t🔹 правый верхний угол, без отступов;\n\
\t🔹 размер - 20% от ширины фоновой картинки;\n\
\t🔹 прозрачность - 0%;\n\
\t🔹 поворот - 0˚.",
        "ro_msg": "Вам запрещено отправлять сюда сообщения в течение 10 минут.",
        "wm_type_msg": "Выберите тип водяного знака.",
        "lang_code": "Выберите язык",
        "video_proc": "Идет обработка видео. Это может занять несколько минут.",
        "photo_received": "Фото получено. Идет обработка.",
        "not_file": "Пожалуйста, пришлите мне изображение или видео как «Фото или видео», а не как «Файл».",
        "more_20": "Размер файла должен быть не более 20 МБ",
        "your_wm": "Чтобы посмотреть, как это выглядит, отправьте мне изображение.",
        "home_page": "Есть два варианта применения бота:\n\
1&#65039;&#8419; Нанесение водяного знака на ваше изображение или видео в чате бота.\n\
2&#65039;&#8419; Использование бота в качестве администратора в канале или группе. \
В этом случае Вы отправляете боту свой вариант водяного знака, настраиваете \
его, а потом добавляете бота в свой канал или группу и назначаете его администратором со следующими правами:\n\
\t&#9989; Публиковать сообщения\n\
\t&#9989; Удалять чужие сообщения\n\
\t&#9989; Редактировать чужие сообщения\n\
После чего на все медиа (кроме аудио😁), отправленные в канал или группу от имени зарегистрированного \
пользователя, автоматически будет наноситься водяной знак, загруженный ранее в боте.",
        "watermark": "Хорошо, новый водяной знак. Пожалуйста, отправьте мне картинку или видео размером не более 20 МБ.\n\
Если вы хотите, чтобы фон водяного знака был прозрачным, предварительно  в удобном вам графическом редакторе удалите фон \
и сохраните файл с расширением GIF или PNG.",
        "new_watermark": "Хорошо, новый водяной знак. Пожалуйста, выберите тип водяного знака."
    },
    "en": {
        "no_watermark": "You don't have a watermark uploaded.",
        "save_success_msg": "Ваш водяной знак готов к использованию.\n\n\
Для теста отправьте мне какую-нибудь картинку, чтобы посмотреть, соотаетсвуют ли настройки вашим ожиданиям.\n\
Вы всегда можете изменить настройки из «Списка команд».",
        "del_msg": "Your watermark was deleted.",
        "setting_completed_msg": "Setting completed.",
        "rotation_select_msg": "Specify the rotation angle of the watermark.\n\nYou can specify 0°, and prepare the image in a graphics editor with rotation.",
        "opacity_select_msg": "Specify the opacity of the watermark.\n\n\t0% - invisible\n\t100% - opaque",
        "size_select_msg": "Specify a size relative to the width of the main image.",
        "pos_select_msg": "Specify the location of the watermark.",
        "under_dev_msg": "<b>UNDER DEVELOPMENT</b>",
        "are_you_shure_msg": "Are you sure you want to remove the watermark?",
        "send_watermark_msg": "Send me your watermart.\n\
&#10071;<b>PLEASE NOTE</b> that if your watermark has a transparent background, then it should be submitted as a «File» and not as a «Photo or Video».\n\
Otherwise, the background will be filled with white.",
        "invalid_type_msg": "Invalid file type.",
        "bad_command_msg": "The command is not recognized.",
        "quick_logo_msg": "To quickly watermark a photo or video, attach two attachments to your message at once, as «Photo or Video», not as «File». The first is the main one, the second is the watermark.\n<b>UNDER DEVELOPMENT</b>",
        "welcome_msg": "Welcome",
        "cmd_list_msg": "I can help you create and manage your watermark.\n\nYou can control me by sending the following commands:\n\n\
            /newlogo - create a new watermark\n\
            /editlogo - edit watermark\n\
            /applylogo - apply a watermark\n\n\
Edit Watermark:\n\
            /setposition - change location\n\
            /setscale - change the size\n\
            /setopacity - change opacity\n\
            /setangle - change rotation\n\
            /setlogopic - change watermark photo\n\
            /delelologo - remove watermark",
        "how_work_msg": "Send me your watrmark you want to test.\n\n\
If you select /wm, the image will be placed on the test image.\n\n\
If you select /bg, your photo or video will be the background and the test logo will be placed on it.\n\
&#10071;<b>PLEASE NOTE</b> that if your watermark has a transparent background, then it should be submitted as a «File» and not as a «Photo or Video».\n\
Otherwise, the background will be filled with white, and black triangles will appear when rotated.\n\n\
Paste options by default:\n\
\t🔹 upper right corner, without indents;\n\
\t🔹 size 20% of the width of the background image;\n\
\t🔹 opacity 100%;\n\
\t🔹 turn 45˚.",
        "ro_msg": "You're not allowed to send messages here for 10 minutes.",
        "wm_type_msg": "Select watermark type.",
        "lang_code": "Choose language",
        "video_proc": "Video processing in progress. This may take several minutes.",
        "photo_received": "Photo received. Processing in progress.",
        "not_file": "Please send me an image or video as «Photo or Video», not as «File».",
        "more_20": "The file size must be no more than 20 MB",
        "your_wm": "To see what it looks like, send me a picture.",
        "home_page": "There are two options for using the bot:\n\
1&#65039;&#8419; Easily apply a watermark to your image or video here in the chat.\n\
2&#65039;&#8419; Using a bot as an admin in a channel or group. \
In this case, you upload (register) your version of the watermark to the bot, set up \
it, and then add the bot to your channel or group and appoint him as an administrator \
with the following rights:\n\
\t&#9989; Post messages\n\
\t&#9989; Delete other people's messages\n\
\t&#9989; Edit other people's messages\n\
After that, all media (except audio😁) sent to the channel or group on behalf of the owner \
or administrator, the watermark uploaded earlier will be automatically applied.",
        "watermark": "Okay, new watermark. Please send me a picture or video no larger than 20 MB.\n\
If you want the background of the watermark to be transparent, first remove the background in \
a graphic editor that is convenient for you and save the file with the GIF or PNG extension.",
        "new_watermark": "Okay, new watermark. Please select a watermark type."
    }}
###############################################################################


################################### BUTTONS ###################################
btn_how_works = InlineKeyboardButton(text = btn_caption.get(language).get('how_it_works_bt'), callback_data ='$HOW_WORKS$')
btn_cmd_list = InlineKeyboardButton(text = btn_caption.get(language).get('cmd_list_bt'), callback_data ='$CMD_LIST$')
btn_signup = InlineKeyboardButton(text = btn_caption.get(language).get('reg_bt'), callback_data ='$SIGN_UP$')
kb_start = InlineKeyboardMarkup(row_width=1).add(btn_how_works, btn_cmd_list, btn_signup)

btn_new_logo = InlineKeyboardButton(text = btn_caption.get(language).get('new_logo_bt'), callback_data ='$NEW_LOGO$')
btn_edit_logo = InlineKeyboardButton(text = btn_caption.get(language).get('edit_logo_bt'), callback_data ='$EDIT_LOGO$')
btn_apply_logo = InlineKeyboardButton(text = btn_caption.get(language).get('apply_logo_bt'), callback_data ='$APPLY_LOGO$')
btn_del_logo = InlineKeyboardButton(text = btn_caption.get(language).get('del_logo_bt'), callback_data ='$DEL_WATERMARK$')
btn_back_start = InlineKeyboardButton(text = btn_caption.get(language).get('come_back_bt'), callback_data ='$BACK_START$')
kb_command_list = InlineKeyboardMarkup(row_width=2).add(btn_new_logo, btn_edit_logo, btn_apply_logo, btn_del_logo, btn_back_start, btn_signup)

kb_standard = InlineKeyboardMarkup(row_width=1).add(btn_cmd_list, btn_back_start)

btn_text_type = InlineKeyboardButton(text = btn_caption.get(language).get('text_type_bt'), callback_data ='$TEXT_TYPE$')
btn_photo_type = InlineKeyboardButton(text = btn_caption.get(language).get('photo_type_bt'), callback_data ='$PHOTO_TYPE$')
# btn_video_type = InlineKeyboardButton(text = btn_caption.get(language).get('video_type_bt'), callback_data ='$VIDEO_TYPE$')
# btn_gif_type = InlineKeyboardButton(text = btn_caption.get(language).get('gif_type_bt'), callback_data ='$GIF_TYPE$')
kb_type_watermark = InlineKeyboardMarkup(row_width=3).add(btn_text_type, btn_photo_type)  # , btn_gif_type
kb_type_watermark.add(btn_back_start)
kb_type_watermark.add(btn_cmd_list)

# kb_apply_wm = InlineKeyboardMarkup(row_width=1).add(btn_cmd_list, btn_back_start)

btn_ok = InlineKeyboardButton(text = 'OK', callback_data ='$OK_DEL_WM$')
btn_no = InlineKeyboardButton(text = btn_caption.get(language).get('no_bt'), callback_data ='$NO_DEL_WM$')
kb_del_wm = InlineKeyboardMarkup(row_width=2).add(btn_ok, btn_no)

btn_nw = InlineKeyboardButton(text = '↖️', callback_data ='$NW$')
btn_n = InlineKeyboardButton(text = '⬆️', callback_data ='$N$')
btn_ne = InlineKeyboardButton(text = '↗️', callback_data ='$NE$')
btn_e = InlineKeyboardButton(text = '➡️', callback_data ='$E$')
btn_se = InlineKeyboardButton(text = '↘️', callback_data ='$SE$')
btn_s = InlineKeyboardButton(text = '⬇️', callback_data ='$S$')
btn_sw = InlineKeyboardButton(text = '↙️', callback_data ='$SW$')
btn_w = InlineKeyboardButton(text = '⬅️', callback_data ='$W$')
btn_c = InlineKeyboardButton(text = '⏹️', callback_data ='$C$')
kb_position = InlineKeyboardMarkup(row_width=3).add(btn_nw, btn_n, btn_ne,  btn_w, btn_c, btn_e, btn_sw, btn_s, btn_se)
kb_position.add(btn_cmd_list)
# kb_position.add(btn_come_back)
btn_save_settings = InlineKeyboardButton(text = btn_caption.get(language).get('save_bt'), callback_data ='$SAVE_LOGO$')
kb_position_edit = InlineKeyboardMarkup(row_width=3).add(btn_nw, btn_n, btn_ne,  btn_w, btn_c, btn_e, btn_sw, btn_s, btn_se)
kb_position_edit.add(btn_save_settings)
kb_position_edit.add(btn_cmd_list)

# btn_come_back = InlineKeyboardButton(text = btn_caption.get(language).get('choose_type_bt'), callback_data ='$NEW_LOGO$')
btn_back_rotation = InlineKeyboardButton(text = btn_caption.get(language).get('change_rotation_bt'), callback_data ='$ROT_SELECT$')
kb_send_file = InlineKeyboardMarkup(row_width=1).add(btn_back_rotation, btn_cmd_list)

kb_file_edit = InlineKeyboardMarkup(row_width=1).add(btn_back_rotation, btn_save_settings, btn_cmd_list)

btn_come_back = InlineKeyboardButton(text = btn_caption.get(language).get('change_pos_bt'), callback_data ='$POS_SELECT$')
btn_num_10 = InlineKeyboardButton(text = '10%', callback_data ='$SIZE_10$')
btn_num_20 = InlineKeyboardButton(text = '20%', callback_data ='$SIZE_20$')
btn_num_30 = InlineKeyboardButton(text = '30%', callback_data ='$SIZE_30$')
btn_num_40 = InlineKeyboardButton(text = '40%', callback_data ='$SIZE_40$')
btn_num_50 = InlineKeyboardButton(text = '50%', callback_data ='$SIZE_50$')
btn_num_60 = InlineKeyboardButton(text = '60%', callback_data ='$SIZE_60$')
btn_num_70 = InlineKeyboardButton(text = '70%', callback_data ='$SIZE_70$')
btn_num_80 = InlineKeyboardButton(text = '80%', callback_data ='$SIZE_80$')
btn_num_90 = InlineKeyboardButton(text = '90%', callback_data ='$SIZE_90$')
btn_num_100 = InlineKeyboardButton(text = '100%', callback_data ='$SIZE_100$')
kb_size_select = InlineKeyboardMarkup(row_width=5).add(btn_num_10, btn_num_20, btn_num_30, btn_num_40, btn_num_50, btn_num_60, btn_num_70, btn_num_80, btn_num_90, btn_num_100)
kb_size_select.add(btn_come_back)
kb_size_select.add(btn_cmd_list)

kb_size_edit = InlineKeyboardMarkup(row_width=5).add(btn_num_10, btn_num_20, btn_num_30, btn_num_40, btn_num_50, btn_num_60, btn_num_70, btn_num_80, btn_num_90, btn_num_100)
kb_size_edit.add(btn_save_settings)
kb_size_edit.add(btn_come_back)
kb_size_edit.add(btn_cmd_list)

btn_come_back = InlineKeyboardButton(text = btn_caption.get(language).get('change_size_bt'), callback_data ='$SIZE_SELECT$')
btn_opacity_0 = InlineKeyboardButton(text = '0%', callback_data ='$OPAC_0$')
btn_opacity_10 = InlineKeyboardButton(text = '10%', callback_data ='$OPAC_10$')
btn_opacity_20 = InlineKeyboardButton(text = '20%', callback_data ='$OPAC_20$')
btn_opacity_30 = InlineKeyboardButton(text = '30%', callback_data ='$OPAC_30$')
btn_opacity_40 = InlineKeyboardButton(text = '40%', callback_data ='$OPAC_40$')
btn_opacity_50 = InlineKeyboardButton(text = '50%', callback_data ='$OPAC_50$')
btn_opacity_60 = InlineKeyboardButton(text = '60%', callback_data ='$OPAC_60$')
btn_opacity_70 = InlineKeyboardButton(text = '70%', callback_data ='$OPAC_70$')
btn_opacity_80 = InlineKeyboardButton(text = '80%', callback_data ='$OPAC_80$')
btn_opacity_90 = InlineKeyboardButton(text = '90%', callback_data ='$OPAC_90$')
# btn_opacity_100 = InlineKeyboardButton(text = '100%', callback_data ='$OPAC_100$')
# kb_opacity_select = InlineKeyboardMarkup(row_width=5).add(btn_opacity_10, btn_opacity_20, btn_opacity_30, btn_opacity_40, btn_opacity_50, btn_opacity_60, btn_opacity_70, btn_opacity_80, btn_opacity_90, btn_opacity_100)
kb_opacity_select = InlineKeyboardMarkup(row_width=5).add(btn_opacity_0, btn_opacity_10, btn_opacity_20, btn_opacity_30, btn_opacity_40, btn_opacity_50, btn_opacity_60, btn_opacity_70, btn_opacity_80, btn_opacity_90)
kb_opacity_select.add(btn_come_back)
kb_opacity_select.add(btn_cmd_list)

kb_opacity_edit = InlineKeyboardMarkup(row_width=5).add(btn_opacity_0, btn_opacity_10, btn_opacity_20, btn_opacity_30, btn_opacity_40, btn_opacity_50, btn_opacity_60, btn_opacity_70, btn_opacity_80, btn_opacity_90)
kb_opacity_edit.add(btn_save_settings)
kb_opacity_edit.add(btn_come_back)
kb_opacity_edit.add(btn_cmd_list)

btn_come_back = InlineKeyboardButton(text = btn_caption.get(language).get('change_opacity_bt'), callback_data ='$OPAC_SELECT$')
btn_rotation_0 = InlineKeyboardButton(text = '⬆️ 0°', callback_data ='$ROT_0$')
btn_rotation_cw45 = InlineKeyboardButton(text = '45° ↗️', callback_data ='$CW_45$')
btn_rotation_cw90 = InlineKeyboardButton(text = '90° ➡️', callback_data ='$CW_90$')
btn_rotation_ccw45 = InlineKeyboardButton(text = '↖️ 45°', callback_data ='$CCW_45$')
btn_rotation_ccw90 = InlineKeyboardButton(text = '⬅️ 90°', callback_data ='$CCW_90$')
kb_rotation_select = InlineKeyboardMarkup(row_width=5).add(btn_rotation_ccw90, btn_rotation_ccw45, btn_rotation_0, btn_rotation_cw45, btn_rotation_cw90)
kb_rotation_select.add(btn_come_back)
kb_rotation_select.add(btn_cmd_list)

kb_rotation_edit = InlineKeyboardMarkup(row_width=5).add(btn_rotation_ccw90, btn_rotation_ccw45, btn_rotation_0, btn_rotation_cw45, btn_rotation_cw90)
kb_rotation_edit.add(btn_save_settings)
kb_rotation_edit.add(btn_come_back)
kb_rotation_edit.add(btn_cmd_list)

btn_go_test = InlineKeyboardButton(text = btn_caption.get(language).get('go_test_bt'), callback_data ='$GO_TEST$')
kb_go_test = InlineKeyboardMarkup(row_width=1).add(btn_signup, btn_go_test, btn_no)

btn_come_back = InlineKeyboardButton(text = btn_caption.get(language).get('other_file_bt'), callback_data ='$PHOTO_TYPE$')
# btn_save_settings = InlineKeyboardButton(text = btn_caption.get(language).get('save_bt'), callback_data ='$SAVE_LOGO$')
btn_cancel_settings = InlineKeyboardButton(text = btn_caption.get(language).get('cancel_all_bt'), callback_data ='$DEL_WATERMARK$')
kb_save_setting = InlineKeyboardMarkup(row_width=1).add(btn_come_back, btn_save_settings, btn_cancel_settings, btn_cmd_list)

kb_save_success = InlineKeyboardMarkup(row_width=1).add(btn_back_start, btn_cmd_list)
######################################################################################################################

########################## START DEF BLOCK #########################
def get_status():

    logo_status = ''

    # if logo_type == '':
    #     logo_status = 'Тип: 🚫 не указан\n'
    # else:
    #     logo_status = f'Тип: «{logo_type}»\n'

    if logo_pos == '':
        logo_status = 'Позиция: 🚫 не указана\n'
    else:
        logo_status = f'Позиция: {logo_pos}\n'

    if logo_size is None:
        logo_status = f'{logo_status}Размер: 🚫 не указан\n'
    else:
        logo_status = f'{logo_status}Размер: {logo_size}%\n'

    if logo_opacity is None:
        logo_status = f'{logo_status}Прозрачность: 🚫 не указана\n'
    else:
        logo_status = f'{logo_status}Прозрачность: {logo_opacity}%\n'

    if logo_angle is None:
        logo_status = f'{logo_status}Поворот: 🚫 не указан\n'
    else:
        logo_status = f'{logo_status}Поворот: {logo_arrow}{abs(logo_angle)}°\n'

    if logo_path == '':
        logo_status = f'{logo_status}Файл: 🚫 не загружен\n'
    else:
        logo_status = f'{logo_status}Файл: ✅ загружен\n'

    if saved_flag:
        logo_status = f'{logo_status}Настройки: ✅ сохранены\n\n'
    else:
        logo_status = f'{logo_status}Настройки: 🚫 не сохранены\n\n'

    return logo_status

def check_sub_channel(chat_member):
    print(chat_member['status'])
    return chat_member['status'] != 'left'

def cmd_list_func(message):
    # global language
    global main_message
    global some_more
    # global logo_type
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    print('cmd_list_func')
    print('user_id:', message.chat.id)
    bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)

    try:
        # user_id = message.from_user.id
        user_id = message.chat.id
        # Загружаем данные из БД
        user_info = db.user_info(user_id)
        print(user_info)
        if user_info is None:
            # logo_type = ''
            logo_path = ''
            logo_pos = ''
            logo_size = None
            logo_opacity = None
            logo_angle = None
            logo_arrow = None
        else:
            if user_info[7] == '' or user_info[7] is None or not os.path.isfile(user_info[7]):
                # logo_type = ''
                logo_path = ''
                logo_pos = ''
                logo_size = None
                logo_opacity = None
                logo_angle = None
                logo_arrow = None
            else:
                # logo_type = user_info[6]
                logo_path = user_info[7]
                logo_pos = user_info[8]
                logo_size = user_info[9]
                logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]

        print('logo_path:', logo_path)
        # Проверяем, есть ли зарегестрированный водяной знак
        if logo_path != '' and os.path.isfile(logo_path):
            PICTURE = logo_path
        else:
            PICTURE = NO_WATERMARK

        with open(PICTURE, 'rb') as photo:
            if some_more or main_message == '':
                bot.delete_message(message.chat.id, message.message_id)
                some_more = False
                main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('cmd_list_msg'), reply_markup=kb_command_list, parse_mode = 'HTML')
            else:
                main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('cmd_list_msg'), parse_mode = 'HTML'), reply_markup=kb_command_list)
    except Exception as e:
        print('cmd_list_func Error:', e)

def back_start_func(message):
    # global language
    global main_message
    global some_more
    print('back_start')
    print('user_id:', message.chat.id)
    print('some_more:', some_more)
    print('No main_message:', main_message == '')

    bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)

    try:
        if message.chat.first_name is not None:
            greeting = f',  {message.chat.first_name}'
        else:
            greeting = ''
        with open(START_PICTURE, 'rb') as photo:
                if some_more or main_message == '':
                    try:
                        bot.delete_message(message.chat.id, message.message_id)
                    except:
                        print('Delete message Error')
                    some_more = False
                    main_message = bot.send_photo(message.chat.id, photo = photo, caption = strings.get(language).get('welcome_msg') + greeting + '!\n\n' + strings.get(language).get('home_page'), reply_markup=kb_start, parse_mode = 'HTML')
                else:
                    main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = strings.get(language).get('welcome_msg') + greeting + '!\n\n' + strings.get(language).get('home_page'), parse_mode='HTML'), reply_markup=kb_start)
    except Exception as e:
        print('back_start Error:', e)

def how_works_func(message):
    # global language
    global main_message
    global some_more
    print('how_works_func')
    print('user_id:', message.chat.id)

    try:
        with open(HOW_WORKS_PICTURE, 'rb') as photo:
            if some_more or main_message == '':
                bot.delete_message(message.chat.id, message.message_id)
                some_more = False
                main_message = bot.send_photo(message.chat.id, photo = photo, caption = strings.get(language).get('how_work_msg'), reply_markup=kb_standard, parse_mode = 'HTML')
            else:
                main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = strings.get(language).get('how_work_msg'), parse_mode='HTML'), reply_markup=kb_standard)
    except Exception as e:
        print('how_works_func Error:', e)

# ################################ EDIT LOGO ###############################
# @bot.message_handler(commands=['editlogo'])
# def edit_logo_handler(message):
#     edit_flag = True
#     bot.delete_message(message.chat.id, message.message_id)
#     edit_logo_func(message)

# def edit_logo_func(message):
#     global edit_flag
#     print('edit_logo_func')

#     user_id = message.chat.id
#     print('user_id:', user_id)
#     print('edit_flag:', edit_flag)

#     if db.user_exists(user_id):
#         try:
#             # Загружаем данные из БД
#             logo_path = db.logo_path(user_id)
#             logo_path = logo_path[0]
#             print('logo_path:', logo_path)

#             if (logo_path == '' and not os.path.isfile(f'watermarks/{user_id}.png')) or (logo_path == f'watermarks/{user_id}.png' and not os.path.isfile(f'watermarks/{user_id}.png')):
#                 print('No path, No file')
#                 return
#             elif os.path.isfile(f'watermarks/{user_id}.png'):
#                 # logo_path = f'watermarks/{user_id}.png'
#                 edit_flag = True
#                 saved_flag = False
#                 pos_selection_func(message)
#                 # photo_waiting_func(message)
#         except Exception as e:
#             print('edit_logo_func Error:', e)
#     else:
#         not_registered_func(message)

@bot.message_handler(commands=['newlogo', 'editlogo', 'setposition'])
def pos_new_func(message):
    global edit_flag
    global new_flag
    print('pos_new_func')
    print('new_flag', new_flag)
    print('edit_flag', edit_flag)
    print('user_id:', user_id)
    bot.delete_message(message.chat.id, message.message_id)
    # match message.text:
    #     case '/newlogo':
    #         new_flag = True
    #         edit_flag = False
    #     case '/editlogo':
    #         if os.path.isfile(f'watermarks/{message.chat.id}.png'):
    #             new_flag = False
    #             edit_flag = True
    #         else:
    #             new_flag = False
    #             edit_flag = False
    #             return
    #     case '/setposition':
    #         if os.path.isfile(f'watermarks/{message.chat.id}.png'):
    #             new_flag = False
    #             edit_flag = True
    #         else:
    #             new_flag = False
    #             edit_flag = False
    #             return

    if message.text == '/newlogo':
        new_flag = True
        edit_flag = False
    elif message.text == '/editlogo':
        if os.path.isfile(f'watermarks/{message.chat.id}.png'):
            new_flag = False
            edit_flag = True
        else:
            new_flag = False
            edit_flag = False
            return
    elif message.text == '/setposition':
        if os.path.isfile(f'watermarks/{message.chat.id}.png'):
            new_flag = False
            edit_flag = True
        else:
            new_flag = False
            edit_flag = False
            return
    else:
        return

    pos_selection_func(message)

########################## POSITION ##########################
def pos_selection_func(message):
    # Ожидание файла
    # Выбор положения водяного знака
    # global language
    global main_message
    # global logo_type
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global new_flag
    global from_pos
    # global user_id
    print('pos_selection_func')
    print('1. logo_path:', logo_path)
    user_id = message.chat.id
    print('user_id:', user_id)
    print('message.text:', message.text)

    if db.user_exists(user_id):
        try:
            if edit_flag:
                if not os.path.isfile(f'watermarks/{message.chat.id}.png'):
                    print('RETURN')
                    edit_flag = False
                    return
                keyboard = kb_position_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                logo_pos = user_info[8]
                logo_size = user_info[9]
                logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            else:
                keyboard = kb_position
                logo_path = ''
                logo_pos = ''
                logo_size = None
                logo_opacity = None
                logo_angle = None
                logo_arrow = ''
                PICTURE = NO_WATERMARK

            # print('open picture:', PICTURE)
            print('some_more:', some_more)
            print('new_flag:', new_flag)
            print('edit_flag:', edit_flag)
            print('message.text:', message.text)
            print('message.id:', message.message_id)
            if main_message != '': print('main_message.id:', main_message.id)

            with open(PICTURE, 'rb') as photo:
                if  (new_flag or edit_flag) and main_message != '':
                    main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('pos_select_msg'), parse_mode='HTML'), reply_markup=keyboard)
                else:
                    bot.delete_message(message.chat.id, message.message_id)
                    main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('pos_select_msg'), reply_markup=keyboard, parse_mode = 'HTML')
        except Exception as e:
            print('pos_selection_func Error:', e)
    else:
        not_registered_func(message)

@bot.message_handler(commands=['setscale'])
def size_selection_handler(message):
    global edit_flag
    edit_flag = True
    bot.delete_message(message.chat.id, message.message_id)
    size_selection_func(message)

def size_selection_func(message):
    # global language
    global main_message
    global some_more
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global from_size
    print('size_selection_func')
    user_id = message.chat.id
    print('user_id:', user_id)
    print('some_more:', some_more)
    print('edit_flag:', edit_flag)
    print('No main_message:', main_message == '')

    bot.clear_step_handler_by_chat_id(chat_id=user_id)

    if db.user_exists(user_id):
    # if check_reg(message):
        try:
            wm_type = message.content_type
            # Проверяем, есть ли зарегестрированный водяной знак
            print('edit_flag:', edit_flag)
            if edit_flag:
                keyboard = kb_size_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                # logo_pos = user_info[8]
                logo_size = user_info[9]
                logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            else:
                keyboard = kb_size_select
                logo_path = ''
                # logo_pos = ''
                logo_size = None
                logo_opacity = None
                logo_angle = None
                logo_arrow = ''
                PICTURE = NO_WATERMARK

            with open(PICTURE, 'rb') as photo:
                print('wm_type:', wm_type)
                print('message.text:', message.text)
                print('some_more:', some_more)
                if wm_type == 'photo' or wm_type == 'document' or message.text == '/setscale':
                    if some_more or main_message == '':
                        main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('size_select_msg'), reply_markup=keyboard, parse_mode = 'HTML')
                    else:
                        main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('size_select_msg'), parse_mode='HTML'), reply_markup=keyboard)
                    some_more = False
                    from_size = True
        except Exception as e:
            print('size_selection_func Error:', e)
    else:
        not_registered_func(message)

@bot.message_handler(commands=['setopacity'])
def opacity_selection_handler(message):
    global edit_flag
    edit_flag = True
    bot.delete_message(message.chat.id, message.message_id)
    opacity_selection_func(message)

def opacity_selection_func(message):
    # global language
    global main_message
    global some_more
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global from_size
    global from_opacity
    print('opacity_selection_func')
    user_id = message.chat.id
    print('user_id:', user_id)
    print('some_more:', some_more)
    print('edit_flag:', edit_flag)
    print('No main_message:', main_message == '')

    if db.user_exists(user_id):
    # if check_reg(message):
        try:
            wm_type = message.content_type
            # Проверяем, есть ли зарегестрированный водяной знак
            print('edit_flag:', edit_flag)
            if edit_flag and not from_size:
                keyboard = kb_opacity_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                logo_pos = user_info[8]
                # logo_size = user_info[9]
                logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            elif edit_flag and from_size:
                keyboard = kb_opacity_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                # logo_pos = user_info[8]
                # logo_size = user_info[9]
                logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            else:
                keyboard = kb_opacity_select
                logo_path = ''
                # logo_pos = ''
                # logo_size = None
                logo_opacity = None
                logo_angle = None
                logo_arrow = ''
                PICTURE = NO_WATERMARK

            with open(PICTURE, 'rb') as photo:
                if wm_type == 'photo' or wm_type == 'document' or message.text == '/setopacity':
                    if some_more or main_message == '':
                        main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('opacity_select_msg'), reply_markup=keyboard, parse_mode = 'HTML')
                    else:
                        main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('opacity_select_msg'), parse_mode='HTML'), reply_markup=keyboard)
                    some_more = False
                    from_size = False
                    from_opacity = True
        except Exception as e:
            print('opacity_selection_func Error:', e)
    else:
        not_registered_func(message)

@bot.message_handler(commands=['setangle'])
def rotation_selection_handler(message):
    bot.delete_message(message.chat.id, message.message_id)
    rotation_selection_func(message)

def rotation_selection_func(message):
    # global language
    global main_message
    global some_more
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global from_size
    global from_opacity
    global from_rotation
    print('rotation_selection_func')
    user_id = message.chat.id
    print('user_id:', user_id)

    if db.user_exists(user_id):
    # if check_reg(message):
        try:
            if  message.text == '/setangle': edit_flag = True
            wm_type = message.content_type
            # Проверяем, есть ли зарегестрированный водяной знак
            if edit_flag and not from_opacity:
                keyboard = kb_rotation_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                logo_pos = user_info[8]
                logo_size = user_info[9]
                # logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            elif edit_flag and from_opacity:
                keyboard = kb_rotation_edit
                user_info = db.user_info(user_id)
                print('user_info =', user_info)
                logo_path = user_info[7]
                # logo_pos = user_info[8]
                # logo_size = user_info[9]
                # logo_opacity = user_info[10]
                logo_angle = user_info[11]
                logo_arrow = user_info[12]
                PICTURE = logo_path
            else:
                keyboard = kb_rotation_select
                logo_path = ''
                # logo_pos = ''
                # logo_size = None
                # logo_opacity = None
                logo_angle = None
                logo_arrow = ''
                PICTURE = NO_WATERMARK

            with open(PICTURE, 'rb') as photo:
                if wm_type == 'photo' or wm_type == 'document' or message.text == '/setangle':
                    if some_more or main_message == '':
                        main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('rotation_select_msg'), reply_markup=keyboard, parse_mode = 'HTML')
                    else:
                        main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('rotation_select_msg'), parse_mode='HTML'), reply_markup=keyboard)
                    some_more = False
                    from_opasity = False
                    from_rotation = True
        except Exception as e:
            print('rotation_selection_func Error:', e)
    else:
        not_registered_func(message)
############################ WAITING PHOTO ############################
@bot.message_handler(commands=['setlogopic'])
def photo_waiting_handler(message):
    edit_flag = True
    bot.delete_message(message.chat.id, message.message_id)
    photo_waiting_func(message)

def photo_waiting_func(message):
    # global language
    global main_message
    global some_more
    # global user_id
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global save_flag
    print('photo_waiting_func')
    user_id = message.chat.id
    print('user_id:', user_id)

    if db.user_exists(user_id):
        try:
            print('some_more:', some_more)
            if edit_flag:
                keyboard = kb_file_edit
                user_info = db.user_info(user_id)
                # print('user_info =', user_info)
                logo_path = user_info[7]
                # logo_pos = user_info[8]
                # logo_size = user_info[9]
                # logo_opacity = user_info[10]
                # logo_angle = user_info[11]
                # logo_arrow = user_info[12]
                PICTURE = logo_path
            else:
                keyboard = kb_send_file
                logo_path = ''
                # logo_pos = ''
                # logo_size = None
                # logo_opacity = None
                # logo_angle = None
                # logo_arrow = ''
                PICTURE = NO_WATERMARK

            with open(PICTURE, 'rb') as photo:
                if some_more or main_message == '':
                    main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('send_watermark_msg'), reply_markup=keyboard, parse_mode = 'HTML')
                else:
                    main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('send_watermark_msg'), parse_mode='HTML'), reply_markup=keyboard)
                some_more = False
            # Регистрация следующего шага (ожидание получения файла функцией pos_selection_func и предложение выбора положения)
            bot.register_next_step_handler(message, setting_completed_func)
        except Exception as e:
            print('photo_waiting_func Error:', e)
    else:
        not_registered_func(message)
############################ SETTING COMPLETED ############################
def setting_completed_func(message):
    global language
    global main_message
    global some_more
    global logo_path
    print('setting_completed_func')
    user_id = message.chat.id
    print('user_id:', user_id)

    if db.user_exists(user_id):
        try:
            # some_more = 1
            # Определяем тип контента. (animation, photo, document)
            wm_type = message.content_type

            print('content_type:', wm_type)

            if wm_type == 'document':
                try: # Делаем проверку по mime_type
                    print('mime_type:', message.document.mime_type)
                    if message.document.mime_type is None:
                        # Если не медиафайл отпрвляем сообщение и выходим из функции
                        some_more = True
                        bot.send_message(message.chat.id, text=strings.get(language).get("invalid_type_msg"))
                        return
                    else:
                        # Определяем тип файла
                        # print('mime_type:', message.document.mime_type[:5])
                        mime_type, file_type = message.document.mime_type.split('/')
                        print(mime_type, file_type)
                        if mime_type == 'image':
                            file_id = message.document.file_id
                            file_info = bot.get_file(file_id)
                        else:
                            some_more = True
                            bot.send_message(message.chat.id, text=strings.get(language).get("invalid_type_msg"))
                            return
                except Exception as e:
                    some_more = True
                    bot.send_message(message.chat.id, e)
                    bot.register_next_step_handler(message, setting_completed_func)
                    return

            elif wm_type == 'photo' and not edit_flag:
                photo = message.photo[len(message.photo)-1]
                file_info = bot.get_file(photo.file_id)
            elif wm_type == 'animation':
                fil_id = message.animation.file_id
                file_info = bot.get_file(file_id)
            elif wm_type == 'text':
                some_more = True
                bot.send_message(message.chat.id, 'Я всё ещё ожидаю файл')  # text=strings.get(language).get("invalid_type_msg"))
                bot.register_next_step_handler(message, pos_selection_func)
                print('setting_completed_func text received')
                return
            else:
                some_more = True
                bot.send_message(message.chat.id, text=strings.get(language).get("invalid_type_msg"))
                bot.register_next_step_handler(message, pos_selection_func)
                return


            logo_path = file_info.file_path
            print('2. logo_path:', logo_path)
            index_point = logo_path.index('.')
            logo_ext = logo_path[index_point:]
            logo_path = f'watermarks/{user_id}.png'
            print('3. logo_path:', logo_path)
            downloaded_file = bot.download_file(file_info.file_path)

            if os.path.isfile(logo_path): os.remove(logo_path) # Если есть такой файл, удаляем

            with open(logo_path, 'wb') as new_photo:
                new_photo.write(downloaded_file)

            # # Проверяем, есть ли зарегестрированный водяной знак
            # if logo_path != '' and os.path.isfile(logo_path):
            #     PICTURE = logo_path
            # else:
            #     PICTURE = NO_WATERMARK

            # with open(PICTURE, 'rb') as photo:
            with open(logo_path, 'rb') as photo:
                if wm_type == 'photo' or wm_type == 'document':
                    bot.delete_message(message.chat.id, message.message_id)
                    if some_more or main_message == '':
                        # bot.delete_message(message.chat.id, message.message_id)
                        some_more = False
                        main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('setting_completed_msg'), reply_markup=kb_save_setting, parse_mode = 'HTML')
                    else:
                        main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('setting_completed_msg'), parse_mode='HTML'), reply_markup=kb_save_setting)
        except Exception as e:
            print('setting_completed_func Error:', e)
    else:
        not_registered_func(message)

@bot.message_handler(commands=['delelogo'])
def del_watermark_handler(message):
    global some_more
    print('user_id:',message.chat.id)
    if db.user_exists(message.chat.id):
        bot.delete_message(message.chat.id, message.message_id)
        if os.path.isfile(f'watermarks/{message.chat.id}.png'):
            print(strings.get(language).get('are_you_shure_msg'))
            some_more = True
            bot.send_message(message.chat.id, strings.get(language).get('are_you_shure_msg'), reply_markup = kb_del_wm, parse_mode = 'HTML')
        else:
            print('No file')
    else:
        not_registered_func(message)

def del_watermark_func(message):
    global main_message
    global some_more
    # global logo_type
    global logo_path
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global new_flag
    print('del_watermark')
    print('user_id:', message.chat.id)
    user_id = message.chat.id

    # Проверяем, есть ли регистрация
    if db.user_exists(user_id):
        print('new_flag:', new_flag)
        new_flag = False
        some_more = True
        cnt = 5
        bot.delete_message(user_id, message.message_id)
        del_msg = bot.send_message(user_id, strings.get(language).get("del_msg"), parse_mode = 'HTML')
        while cnt > 0:
            del_msg = bot.edit_message_text(chat_id=user_id, message_id=del_msg.message_id, text=str(cnt) + ' ' + strings.get(language).get("del_msg"), parse_mode = 'HTML')
            cnt -= 1
            time.sleep(1)

        bot.delete_message(user_id, del_msg.message_id)
        some_more = False
        print('delete_message OK')

        # Если есть файл. удаляем
        if os.path.isfile(f'watermarks/{user_id}.png'): os.remove(f'watermarks/{user_id}.png')
        print('remove file OK')
        # print('main_message:', main_message)
        try:
            # Очищаем переменные
            # logo_type = ''
            logo_path = ''
            logo_pos = ''
            logo_size = None
            logo_opacity = None
            logo_angle = None
            logo_arrow = None
            # Сохраняем базу данных с пустыми значениями
            save_logo_func(message)
            print('save_logo OK')
        except:
            pass
        with open(NO_WATERMARK, 'rb') as photo:
            main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('cmd_list_msg'), parse_mode='HTML'), reply_markup=kb_command_list)

    else:
        not_registered_func(message)

def get_id(user_name):
    print('get_id')
    print('user_id:', message.chat.id)

    try:
        ID = bot.get_chat(user_name).id
        print(ID2)
    except Exception as e:
        print(e)

def save_logo_func(message):
    global main_message
    global some_more
    global edit_flag
    global new_flag
    global saved_flag
    # global logo_type
    # global logo_path
    # global logo_pos
    # global logo_size
    # global logo_opacity
    # global logo_angle
    # global logo_arrow
    print('save_logo_func')
    user_id = message.chat.id
    print('user_id:', user_id)

    try:
        if db.user_exists(message.chat.id):
            try:
                print(logo_path, logo_pos, logo_size, logo_opacity, logo_angle, logo_arrow, user_id)
                print(db.save_logo(logo_path, logo_pos, logo_size, logo_opacity, logo_angle, logo_arrow, user_id))
                wm_type = message.content_type
                # Проверяем, есть ли зарегестрированный водяной знак
                if logo_path != '' and os.path.isfile(logo_path):
                    PICTURE = logo_path
                else:
                    PICTURE = NO_WATERMARK

                with open(PICTURE, 'rb') as photo:
                    if wm_type == 'photo' or wm_type == 'document':
                        saved_flag = True
                        if some_more or main_message == '':
                            bot.delete_message(message.chat.id, message.message_id)
                            some_more = False
                            main_message = bot.send_photo(message.chat.id, photo = photo, caption = get_status() + strings.get(language).get('save_success_msg'), reply_markup=kb_save_setting, parse_mode = 'HTML')
                        else:
                            main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = get_status() + strings.get(language).get('save_success_msg'), parse_mode='HTML'), reply_markup=kb_save_success)
                edit_flag = False
                new_flag = False
                # Отменям next_step_register
                bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
            except Exception as e:
                print(e)
    except Exception as e:
        print(e)

def not_registered_func(message):
    try:
        bot.delete_message(message.chat.id, message.message_id)
        bot.send_message(message.chat.id, 'Вы не являетесь зарегистрированным пользователем. Вам доступна только функция тестирования вашего водяного знака', reply_markup=kb_go_test, parse_mode = 'HTML')
    except Exception as e:
        print('Not registered Error', e)
######################## END DEF BLOCK ########################

############################# START HENDLERS #############################
################################ ADD TEXT ###############################
@bot.message_handler(commands=['txt'])
def add_text_func(message):
    from datetime import datetime
    global some_more
    user_id = message.chat.id
    print('add_text_func')
    print('user_id:', user_id)
    # os.system(f'ffmpeg -i sourses/background.jpeg -vf "drawtext=fontfile=/path/to/font.ttf:text='Stack Overflow':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2" -codec:a copy output.png")
    # os.system(f'ffmpeg -y -i sources/background.jpeg -vf "drawtext=text=\'TEST TEXT\':fontcolor=green:fontsize=48:box=1:boxcolor=black@0.2:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2" output.png')
    # Рисует одну зеленую букву «g» в центре входного видео. Базовая линия глифа располагается на половине высоты экрана.
    # os.system(f'ffmpeg -y -i sources/background.jpeg -vf "drawtext=fontsize=60:fontfile=FreeSerif.ttf:fontcolor=green:text=g:x=(w-max_glyph_w)/2:y=h/2-ascent" {user_id}.png')

    # Рисует «Тестовый текст» шрифтом FreeSerif размером 24 в позиции x=100 и y=50 (считая от верхнего левого угла экрана), текст будет желтым с красной рамкой вокруг него. И текст, и поле имеют непрозрачность 20%.
    # os.system(f'ffmpeg -y -i sources/background.jpeg -vf drawtext="fontfile=FreeSerif.ttf:text=\'Тестовый текст\':x=100:y=50:fontsize=24:fontcolor=yellow@0.2:box=1:boxcolor=red@0.2:rotate=90" {user_id}.png')
    # Рисует «Тестовый текст» с размером шрифта, зависящим от высоты видео.
    start_time = datetime.now()
    os.system(f'ffmpeg -y -i sources/background.png -vf "rotate=30,drawtext=text=\'Ваш текст\':fontsize=48:fontcolor=white:x=10:y=10:fix_bounds=True,rotate=-30" {user_id}.png')
    print(datetime.now() - start_time)

    # os.system(f'ffmpeg -y -loglevel panic\
    #     -i {background} \
    #     -i {logo} \
    #     -filter_complex \
    #     "[1][0]scale2ref=h=ow/mdar:w=iw*{scale}[logo][main_photo];\
    #     [logo] rotate={angle}:fillcolor=0x00000000,\
    #     format=argb,\
    #     colorchannelmixer=aa={alpha}[logo_transparent];\
    #     [main_photo][logo_transparent]overlay={overlay}"\
    #     {user_id}.png')

    # ffmpeg -i input.mp4 -vf "scale=iw*sar:ih,rotate=90" output.mp4
    # Здесь параметр iw обозначает исходную ширину, ih - высоту. sar используется для сохранения соотношения сторон. Фильтр rotate поворачивает изображение на 90 градусов.
############################ APPLY WATERMARKS ############################
@bot.message_handler(commands=['applylogo'])
def apply_watermark_func(message):
    # global language
    global main_message
    global some_more
    print('apply_watermark_func')
    print('user_id:', message.chat.id)

    if db.user_exists(message.chat.id):
    # if check_reg(message):
        try:
            if message.text == '/applylogo':
                message_id = message.message_id - 1
                bot.delete_message(message.chat.id, message.message_id)
                some_more = False
            else:
                message_id = message.message_id

            with open(APPLY_PICTURE, 'rb') as animation:
                print('some_more:', some_more, 'main_message:', main_message)
                if some_more or main_message == '':
                    # bot.delete_message(message.chat.id, message.message_id)
                    some_more = False
                    main_message = bot.send_animation(message.chat.id, animation, caption = strings.get(language).get('under_dev_msg'), reply_markup=kb_standard, parse_mode='HTML')  # отправляем анимацию
                    # main_message = bot.send_photo(message.chat.id, photo = photo, caption = strings.get(language).get('new_watermark'), reply_markup=kb_type_watermark, parse_mode = 'HTML')
                else:
                    main_message = bot.edit_message_media(chat_id=message.chat.id, message_id=main_message.message_id, media=telebot.types.InputMediaAnimation(media=animation, caption = strings.get(language).get('under_dev_msg'), parse_mode='HTML'), reply_markup=kb_standard)
            # file_name = 'demo-1.gif'
            # with open(file_name, 'rb') as caption_pic:
            #     bot.send_animation(chat_id, caption_pic, caption = strings.get(language).get("quick_logo"), parse_mode = 'HTML')
        except Exception as e:
            print('apply_watermark_func Error:', e)
    else:
        not_registered_func(message)

@bot.message_handler(commands=['add'])
def add_func(message):
    print('add_func')
    print('user_id:', message.chat.id)
    _, user_id = message.text.split(maxsplit=1)
    db.add_user(user_id)


############################# START #############################
@bot.message_handler(commands=['start'])
def start_func(message):
    # global language
    global main_message
    global some_more

    print('start_func')
    print('user_id:', message.chat.id)
    print('some_more:', some_more)
    bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)

    if message.chat.type == 'private':
        if message.chat.first_name is not None:
            greeting = f',  {message.chat.first_name}'
        else:
            greeting = ''
        # except Exception as e:
        #     print("Keyboard error:", e)
        #     some_more = 1
        #     bot.send_message(message.chat.id, f'Keyboard error: {e}')
        try:
            with open(START_PICTURE, 'rb') as photo:
                if some_more or main_message == '':
                    bot.delete_message(message.chat.id, message.message_id)
                    some_more = False
                main_message = bot.send_photo(message.chat.id, photo = photo, caption = strings.get(language).get('welcome_msg') + greeting + '!\n\n' + strings.get(language).get('home_page'), reply_markup=kb_start, parse_mode = 'HTML')
        except Exception as e:
            print("start_func error:", e)
            some_more = True
            bot.send_message(message.chat.id, f'Send error: {e}')

############################ RESTART ############################
@bot.message_handler(commands=['restart'])
def restart_func(message):
    global some_more
    some_more = True
    print('restart_func')
    print('from_user.id', message.chat.id)
    bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)

    if db.user_exists(message.chat.id):
    # if check_reg(message):
        try:
            bot.send_message(message.chat.id, "Bot is restarting...")
            os.execl(sys.executable, sys.executable, *sys.argv)
        except Exception as e:
            print('restart_func Error:', e)
    else:
        not_registered_func(message)

############################ HELP ############################
# @bot.message_handler(commands=['help'])
# def help(message):
#     # msg = """Повторяйте за мной:
#     # &#128591;
#     # Отче наш, сущий на небесах!
#     # Да святится имя Твое..."""
#     bot.send_message(message.chat.id, HELP, parse_mode = 'HTML')


#################### GET ID  BY NAME #####################
# @bot.channel_post_handler(commands=['get'])
# @bot.message_handler(commands=['get'])
# def getIdByName(message):
#     global some_more
#     print('getIdByName')


#     try:
#         _, name = message.text.split()
#         print(name)

#         bot_id = bot.get_chat(name).id
#         print(bot_id)

#         bot.send_message(message.chat.id, f'ID: {bot_id}')
#         some_more = True
#         bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
#     except Exception as e:
#         print(e)
# ####################### MY ID #######################
# @bot.channel_post_handler(commands=['id'])
# @bot.message_handler(commands=['id'])
# def my_id(message):
#     global some_more
#     some_more = True
#     bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
#     print('my_id')
#     if message.from_user is None:
#         bot.send_message(message.chat.id, f'chat_ID: {message.chat.id}')
#     else:
#         bot.send_message(message.chat.id, f'user_ID: {message.from_user.id}')

# @bot.channel_post_handler()
# @bot.message_handler(func=lambda message: message.chat.type in ['channel', 'group', 'supergroup'])
# def on_group_message(message):
#     # if message.from_user.id == bot.get_me().id:
#     #     print("Bot added to group:", message.chat.title)
#     print(message)

@bot.channel_post_handler(content_types=CONTENT_TYPES)
def my_function(message):
    chat_id = message.chat.id
    print(f'chat_id: {chat_id}  content_types: {message.chat.type}')
    # who_added_bot = chat_id
    # print(who_added_bot)
    # if who_added_bot == 'channel_admin': # замените 'channel_admin' на имя администратора вашего канала
    #     print('Мой бот был успешно добавлен в канал')
    # else:
    #     print('Мой бот еще не был добавлен в канал')

############################ VIDEO ############################
@bot.message_handler(content_types=['video'])
# @bot.channel_post_handler(content_types=['video'])
def get_video(message):
    global some_more
    some_more = True
    print('get_video')
    print('user_id:', message.chat.id)

    if db.user_exists(message.chat.id):
        # try:
            video = message.video
            file_info = bot.get_file(video.file_id)
            print('Size:', video.file_size, '  Width:', video.width, '  Height:', video.height )

            overlay = 'W-w-1:1'
            alpha = 1
            caption = message.caption
            scale = 0.2
            if caption:
                print('Caption:', caption)
                caption = message.caption.lower()
                # Парсим аргументы
                arguments = caption.split()
                for arg in arguments:
                    if arg[0] == '-':
                        if arg[1] == 'p':
                            pos = arg[2:]
                            if pos == 'n':
                                overlay = '(main_w-w)/2:1'
                            elif pos == 'ne':
                                overlay = 'W-w-1:1'
                            elif pos == 'e':
                                overlay = '(main_w-w):(main_h-h)/2'
                            elif pos == 'se':
                                overlay = 'W-w-1:H-h-1'
                            elif pos == 's':
                                overlay = '(main_w-w)/2:main_h-h'
                            elif pos == 'sw':
                                overlay = '1:H-h-1'
                            elif pos == 'w':
                                overlay = '1:(main_h-h)/2'
                            elif pos == 'nw':
                                overlay = '1:1'
                            elif pos == 'c':
                               overlay = '(main_w-w)/2:(main_h-h)/2'
                        elif arg[1] == 's':
                            scale = arg[2:]
                        elif arg[1] == 'o':
                            alpha = int(arg[2:])/100
                            
                        # Не работает в Python3.8.6    
                        # match arg[1]:
                        #     case 'p': # position
                        #         pos = arg[2:]
                        #         match pos:
                        #             case 'n':
                        #                 overlay = '(main_w-w)/2:1'
                        #             case 'ne':
                        #                 overlay = 'W-w-1:1'
                        #             case 'e':
                        #                 overlay = '(main_w-w):(main_h-h)/2'
                        #             case 'se':
                        #                 overlay = 'W-w-1:H-h-1'
                        #             case 's':
                        #                 overlay = '(main_w-w)/2:main_h-h'
                        #             case 'sw':
                        #                 overlay = '1:H-h-1'
                        #             case 'w':
                        #                 overlay = '1:(main_h-h)/2'
                        #             case 'nw':
                        #                 overlay = '1:1'
                        #             case 'c':
                        #                 overlay = '(main_w-w)/2:(main_h-h)/2'
                        #     case 's': # scale
                        #         scale = arg[2:]
                        #     case 'o': # opacity(alpha)
                        #         alpha = int(arg[2:])/100

                    else:
                        caption = message.caption

            else:
                print('Caption: None')
                # Устанавливаем значения из БД
                # В данный момент - по умолчанию
                overlay = 'W-w-1:1'
                alpha = 1
                scale = 0.2
                caption = ''

            file_info = bot.get_file(message.video.file_id)
            print(file_info)
            downloaded_file = bot.download_file(file_info.file_path)

            src = file_info.file_path
            print(src)
            with open(src, 'wb') as new_video:
                new_video.write(downloaded_file)

            some_more = True
            record_process = bot.send_message(message.chat.id, strings.get(language).get("video_proc"))

            """
            Center:
            overlay=(main_w-w)/2:(main_h-h)/2
            Top left corner:
            overlay=1:1
            Top right corner:
            overlay=W-w-1:1
            lower right corner:
            overlay=W-w-1:H-h-1
            Bottom left corner:
            overlay=1:H-h-1
            Bottom right corner. Padding 10px to the right and -10px to the bottom:
            overlay=main_w-w/1:main_h-h/2
            Bottom right corner. Padding -10px to the right and -10px to the bottom:
            overlay=main_w-w/1:main_h-h/2
            """


            logo = 'sources/logo.png'
            print('Logo path:', logo)

            os.system(f'ffmpeg -y \
                -i {src} \
                -i {logo} \
                -filter_complex "\
                [1][0]scale2ref=h=ow/mdar:w=iw*{scale}[logo][main_video];\
                [logo]format=argb,\
                colorchannelmixer=aa={alpha}[logo_transparent];\
                [main_video][logo_transparent]\
                overlay={overlay}" \
                output.mp4')

            with open('output.mp4', 'rb') as video_1:
                bot.send_video(message.chat.id, video_1)
                bot.delete_message(message.chat.id, message.message_id)
                bot.delete_message(message.chat.id, record_process.message_id)
            os.remove(src)
            os.remove('output.mp4')
            print('Video was deleted')

        # except Exception as e:
        #     if str(e).find('Error code: 400. Description: Bad Request: file is too big'):
        #         some_more = True
        #         bot.send_message(message.chat.id, strings.get(language).get('more_20'))
        #     else:
        #         some_more = True
        #         bot.send_message(message.chat.id, f'ERROR: {e}')
        #     try:
        #         file_path = bot.get_file(message.video.file_id).file_path
        #         os.remove(file_path)
        #         print('Video was deleted')
        #     except Exception as e:
        #         print('Error:', e)
    else:
        not_registered_func(message)
################################## PHOTO ##################################
@bot.message_handler(content_types=['photo', 'document'])
@bot.channel_post_handler(content_types=['photo', 'document'])
def get_photo(message):
    global main_message
    global some_more
    global logo_path
    # global logo_type
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global logo_ext
    global test_flag
    print('get_photo')

    if message.forward_date is None:
        print('chat_type:', message.chat.type)
        if message.chat.type == 'channel':
            print(message.chat.id)
            user_info = db.chat_info(message.chat.id)
            if user_info is None: return
            print('user_info =', user_info)
            user_id = user_info[0]
        else:
            user_id = message.chat.id
            user_info = db.user_info(user_id)
        print('user_id:', user_id)

        if db.user_exists(user_id) or message.caption == '/test':  #test_flag:
            try:
                if not os.path.isfile(f'watermarks/{user_id}.png') and message.caption != '/test':
                    some_more = True
                    cnt = 5
                    bot.delete_message(message.chat.id, message.message_id)
                    del_msg = bot.send_message(message.chat.id, strings.get(language).get("no_watermark"), parse_mode = 'HTML')
                    while cnt > 0:
                        del_msg = bot.edit_message_text(chat_id=message.chat.id, message_id=del_msg.message_id, text=str(cnt) + ' ' + strings.get(language).get("no_watermark"), parse_mode = 'HTML')
                        cnt -= 1
                        time.sleep(1)

                    # time.sleep(5)
                    bot.delete_message(message.chat.id, del_msg.message_id)
                    some_more = False
                    return
                wm_type = message.content_type
                print('user_info:', user_info)
                print('content_type:', wm_type)
                if wm_type == 'document':
                    try:
                        if message.document.mime_type is None:
                            some_more = True
                            bot.send_message(message.chat.id, text=strings.get(language).get("invalid_type_msg"))
                            return
                        else:
                            print('mime_type:', message.document.mime_type[:5])
                            mime_type, logo_ext = message.document.mime_type.split('/')
                            if mime_type == 'image' or mime_type == 'video':
                                document = message.document
                                file_info = bot.get_file(document.file_id)
                            else:
                                some_more = True
                                bot.send_message(message.chat.id, text=strings.get(language).get("invalid_type_msg"))
                                return
                    except Exception as e:
                            some_more = True
                            bot.send_message(message.chat.id, e)
                            return

                elif wm_type == 'photo':
                    photo = message.photo[len(message.photo)-1]
                    file_info = bot.get_file(photo.file_id)

                if message.caption == '/test':
                    logo = file_info.file_path
                    background = 'sources/background-1.jpg'

                    print(f'Downloading logo {logo} "test"')
                    downloaded_file = bot.download_file(logo)

                    with open(logo, 'wb') as new_photo:
                        new_photo.write(downloaded_file)
                else:
                    if message.chat.type == 'channel':
                        logo = f'watermarks/{user_id}.png'  # user_info[7]  #'sources/logo.png'
                    else:
                        # ID = bot.get_chat(chat_name).id
                        logo = user_info[7]  #'sources/logo.png'
                    background = file_info.file_path

                    print('Downloading...')
                    downloaded_file = bot.download_file(background)

                    with open(background, 'wb') as new_photo:
                        new_photo.write(downloaded_file)


                if message.chat.type != 'channel':
                    some_more = True
                    record_process = bot.send_message(message.chat.id, strings.get(language).get("photo_received"))

                """
                Center:
                overlay=(main_w-w)/2:(main_h-h)/2
                Top left corner:
                overlay=1:1
                Top right corner:
                overlay=W-w-1:1
                lower right corner:
                overlay=W-w-1:H-h-1
                Bottom left corner:
                overlay=1:H-h-1
                Bottom right corner. Padding 10px to the right and -10px to the bottom:
                overlay=main_w-w/1:main_h-h/2
                Bottom right corner. Padding -10px to the right and -10px to the bottom:
                overlay=main_w-w/1:main_h-h/2
                """

        ############################# OS.SYSTEM ####################################
                if message.caption == '/test':
                    # Устанавливаем значения по умолчанию
                    overlay = 'W-w-1:1'
                    scale = 0.2
                    alpha = 1
                    angle = 0
                else:
                    # Устанавливаем значения из БД
                    # Position (overlay)
                    if user_info[8] == '⬆️':
                        overlay = '(main_w-w)/2:1'
                    elif user_info[8] == '↗️':
                        overlay = 'W-w-1:1'
                    elif user_info[8] == '➡️':
                        overlay = '(main_w-w):(main_h-h)/2'
                    elif user_info[8] == '↘️':
                        overlay = 'W-w-1:H-h-1'
                    elif user_info[8] == '⬇️':
                        overlay = '(main_w-w)/2:main_h-h'
                    elif user_info[8] == '↙️':
                        overlay = '1:H-h-1'
                    elif user_info[8] == '⬅️':
                        overlay = '1:(main_h-h)/2'
                    elif user_info[8] == '↖️':
                        overlay = '1:1'
                    elif user_info[8] == '⏹️':
                        overlay = '(main_w-w)/2:(main_h-h)/2'
                    
                    # match user_info[8]:
                    #     case '⬆️':
                    #         overlay = '(main_w-w)/2:1'
                    #     case '↗️':
                    #         overlay = 'W-w-1:1'
                    #     case '➡️':
                    #         overlay = '(main_w-w):(main_h-h)/2'
                    #     case '↘️':
                    #         overlay = 'W-w-1:H-h-1'
                    #     case '⬇️':
                    #         overlay = '(main_w-w)/2:main_h-h'
                    #     case '↙️':
                    #         overlay = '1:H-h-1'
                    #     case '⬅️':
                    #         overlay = '1:(main_h-h)/2'
                    #     case '↖️':
                    #         overlay = '1:1'
                    #     case '⏹️':
                    #         overlay = '(main_w-w)/2:(main_h-h)/2'

                    scale = user_info[9]/100
                    alpha = (100 - user_info[10])/100
                    angle = user_info[11]*3.1415926/180

                print('logo:', logo)
                print('angle:', angle)
                print('background:', background)
                print('Converting...')#

                os.system(f'ffmpeg -y -loglevel panic\
                    -i {background} \
                    -i {logo} \
                    -filter_complex \
                    "[1][0]scale2ref=h=ow/mdar:w=iw*{scale}[logo][main_photo];\
                    [logo] rotate={angle}:c=none:ow=rotw({angle}):oh=roth({angle}),colorchannelmixer=aa={alpha}[logo_transparent];\
                    [main_photo][logo_transparent]overlay={overlay}"\
                    {user_id}.png')

                # os.system(f'ffmpeg -y -i {background} -i {logo} -filter_complex "[1:v]rotate=45*{PI}/180[rotate];[0:v][rotate]overlay=W-w*0.85:H-h*0.85" {user_id}.png')

                # os.system(f'ffmpeg -y -i {background} -i {logo} -filter_complex "[1:v]rotate={angle}:c=none:ow=rotw({angle}):oh=roth({angle}),colorchannelmixer=aa={alpha},scale2ref=iw*{scale}:-1[rotate];[0:v][rotate]overlay={overlay}" {user_id}.png')

    ############################################################################
    ############################################################################
                path = f'{user_id}.png'
                print('path:', path)
                print('isfile:', os.path.isfile(path))
                # time.sleep(10)
                with open(f'{user_id}.png', 'rb') as photo:
                    if message.chat.type == 'channel':
                        if message.caption is None:
                            bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, parse_mode='HTML'))
                        else:
                            bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=telebot.types.InputMedia(type='photo', media=photo, caption = message.caption+' ', parse_mode='HTML'))
                    else:
                        bot.delete_message(message.chat.id, message.message_id)
                        bot.delete_message(message.chat.id, record_process.message_id)
                        if message.caption is None:
                            bot.send_photo(message.chat.id, photo, parse_mode = 'HTML')
                        else:
                            bot.send_photo(message.chat.id, photo, caption = message.caption, parse_mode = 'HTML')


                if message.caption == '/test':
                    print('Removing logo')
                    os.remove(logo)
                elif message.caption is None:
                    print('Removing background')
                    os.remove(background)
                os.remove(f'{user_id}.png')
                print('Removing output file')

                print('Photos was deleted')
                print('='*100)
            except Exception as e:
                if str(e).find('Error code: 400. Description: Bad Request: file is too big') != -1:
                    print(e)
                    some_more = True
                    bot.send_message(message.chat.id, strings.get(language).get('more_20'))
                else:
                    some_more = True
                    bot.send_message(message.chat.id, f'ERROR: {e}')
                try:
                    file_path = bot.get_file(message.photo[len(message.photo)-1].file_path)
                    os.remove(file_path)
                    print('Photo was deleted')
                except Exception as e:
                    print('Error:', e)
        else:
            not_registered_func(message)

################################## END PHOTO ####################################
@bot.message_handler(commands=['stop'])
def stop(message):
    bot.send_message(message.chat.id,"Бот остановлен ❌")
    bot.stop_bot()
    
# @bot.message_handler()
# def mess_handler(message):
#     global some_more
#     some_more = 1
#     print('mess_handler')
#     print(message.content_type)
#     # for word in cfg.WORDS:
#     #     if word in text:
#     #         try:
#     #             bot.restrict_chat_member(message.chat.id, message.from_user.id, until_date=time.time()+60,
#     #                                     can_send_messages=None,
#     #                                     can_send_media_messages=None,
#     #                                     can_send_other_messages=None,
#     #                                     can_add_web_page_previews=None)
#     #             some_more = 1
#     #             bot.send_message(message.chat.id, strings.get(language).get("ro_msg"), reply_to_message_id=message.message_id)
#     #             # bot.send_message(message.chat.id, strings.get(get_language(message.from_user.language_code)).get("ro_msg"), reply_to_message_id=message.message_id)
#     #             bot.delete_message(message.chat.id, message.message_id)
#     #         except Exception as e:
#     #             some_more = 1
#     #             bot.send_message(message.chat.id, e, reply_to_message_id=message.message_id)
#     #             print(e)
################################################ LAMBDA ################################################
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
    global language
    global some_more
    # global logo_type
    global logo_pos
    global logo_size
    global logo_opacity
    global logo_angle
    global logo_arrow
    global edit_flag
    global test_flag
    global new_flag
    global saved_flag
    msg = call.message

    try:
        if call.data == '$BACK_START$':
            back_start_func(msg)
        elif call.data == '$CMD_LIST$':
            cmd_list_func(msg)
        elif call.data == '$HOW_WORKS$' or call.data == '$GO_TEST$':
            test_flag = True
            how_works_func(msg)
        elif call.data == '$NEW_LOGO$':
            new_flag = True
            pos_selection_func(msg)
        elif call.data == '$APPLY_LOGO$':
            apply_watermark_func(msg)
        elif call.data == '$NO_DEL_WM$':
            print('Cancel action')
            bot.delete_message(msg.chat.id, msg.message_id)  # Удаляем сообщение
            some_more = False
        elif call.data == '$OK_DEL_WM$':
            del_watermark_func(msg)
        elif call.data == '$DEL_WATERMARK$':
            print('$DEL_WATERMARK$', msg.from_user.id)
            if db.user_exists(msg.chat.id):
                if os.path.isfile(f'watermarks/{msg.chat.id}.png'):
                    print(strings.get(language).get('are_you_shure_msg'))
                    some_more = True
                    bot.send_message(msg.chat.id, strings.get(language).get('are_you_shure_msg'), reply_markup = kb_del_wm, parse_mode = 'HTML')
                else:
                    print('No file')
            else:
                not_registered_func(msg)
        elif call.data == '$EDIT_LOGO$':
            edit_flag = True
            pos_selection_func(msg)
        elif call.data == '$POS_SELECT$':
            pos_selection_func(msg)
        elif call.data == '$SIZE_SELECT$':
            size_selection_func(msg)
        elif call.data == '$OPAC_SELECT$':
           opacity_selection_func(msg)
        elif call.data == '$ROT_SELECT$':
            rotation_selection_func(msg)
        elif call.data == '$SAVE_LOGO$':
            save_logo_func(msg)
        elif call.data == '$TEXT_TYPE$':
            pass
        elif call.data == '$VIDEO_TYPE$':
            pass
        # elif call.data == '$GIF_TYPE$':
        #     logo_type = 'текст'
        #     photo_waiting_func(msg)
        elif call.data == '$C$':
            saved_flag = False
            logo_pos = '⏹️'
            size_selection_func(msg)
        elif call.data == '$N$':
            saved_flag = False
            logo_pos = '⬆️'
            size_selection_func(msg)
        elif call.data == '$NE$':
            saved_flag = False
            logo_pos = '↗️'
            size_selection_func(msg)
        elif call.data == '$E$':
            saved_flag = False
            logo_pos = '➡️'
            size_selection_func(msg)
        elif call.data == '$SE$':
            saved_flag = False
            logo_pos = '↘️'
            size_selection_func(msg)
        elif call.data == '$S$':
            saved_flag = False
            logo_pos = '⬇️'
            size_selection_func(msg)
        elif call.data == '$SW$':
            saved_flag = False
            logo_pos = '↙️'
            size_selection_func(msg)
        elif call.data == '$W$':
            saved_flag = False
            logo_pos = '⬅️'
            size_selection_func(msg)
        elif call.data == '$NW$':
            saved_flag = False
            logo_pos = '↖️'
            size_selection_func(msg)
        elif call.data == '$SIZE_10$':
            saved_flag = False
            logo_size = 10
            opacity_selection_func(msg)
        elif call.data == '$SIZE_20$':
            saved_flag = False
            logo_size = 20
            opacity_selection_func(msg)
        elif call.data == '$SIZE_30$':
            saved_flag = False
            logo_size = 30
            opacity_selection_func(msg)
        elif call.data == '$SIZE_40$':
            saved_flag = False
            logo_size = 40
            opacity_selection_func(msg)
        elif call.data == '$SIZE_50$':
            saved_flag = False
            logo_size = 50
            opacity_selection_func(msg)
        elif call.data == '$SIZE_60$':
            saved_flag = False
            logo_size = 60
            opacity_selection_func(msg)
        elif call.data == '$SIZE_70$':
            saved_flag = False
            logo_size = 70
            opacity_selection_func(msg)
        elif call.data == '$SIZE_80$':
            saved_flag = False
            logo_size = 80
            opacity_selection_func(msg)
        elif call.data == '$SIZE_90$':
            saved_flag = False
            logo_size = 90
            opacity_selection_func(msg)
        elif call.data == '$SIZE_100$':
            saved_flag = False
            logo_size = 100
            opacity_selection_func(msg)
################################################################
        elif call.data == '$OPAC_0$':
            saved_flag = False
            logo_opacity = 0
            rotation_selection_func(msg)
        elif call.data == '$OPAC_10$':
            saved_flag = False
            logo_opacity = 10
            rotation_selection_func(msg)
        elif call.data == '$OPAC_20$':
            saved_flag = False
            logo_opacity = 20
            rotation_selection_func(msg)
        elif call.data == '$OPAC_30$':
            saved_flag = False
            logo_opacity = 30
            rotation_selection_func(msg)
        elif call.data == '$OPAC_40$':
            saved_flag = False
            logo_opacity = 40
            rotation_selection_func(msg)
        elif call.data == '$OPAC_50$':
            saved_flag = False
            logo_opacity = 50
            rotation_selection_func(msg)
        elif call.data == '$OPAC_60$':
            saved_flag = False
            logo_opacity = 60
            rotation_selection_func(msg)
        elif call.data == '$OPAC_70$':
            saved_flag = False
            logo_opacity = 70
            rotation_selection_func(msg)
        elif call.data == '$OPAC_80$':
            saved_flag = False
            logo_opacity = 80
            rotation_selection_func(msg)
        elif call.data == '$OPAC_90$':
            saved_flag = False
            logo_opacity = 90
            rotation_selection_func(msg)
        # elif call.data == '$OPAC_100$':
        #     saved_flag = False
        #     logo_opacity = 100
        #     rotation_selection_func(msg)
################################################################
# arrow_0 = '⬆️'
# arrow_CW_45 = '↗️'
# arrow_CW_90 = '➡️'
# arrow_CCW_45 = '↖️'
# arrow_CCW_90 = '⬅️'
################################################################
        elif call.data == '$ROT_0$':
            saved_flag = False
            logo_arrow = '⬆️'
            logo_angle = 0
            photo_waiting_func(msg)
        elif call.data == '$CW_45$':
            saved_flag = False
            logo_arrow = '↗️'
            logo_angle = 45
            photo_waiting_func(msg)
        elif call.data == '$CW_90$':
            saved_flag = False
            logo_arrow = '➡️'
            logo_angle = 90
            photo_waiting_func(msg)
        elif call.data == '$CCW_45$':
            saved_flag = False
            logo_arrow = '↖️'
            logo_angle = -45
            photo_waiting_func(msg)
        elif call.data == '$CCW_90$':
            saved_flag = False
            logo_arrow = '⬅️'
            logo_angle = -90
            photo_waiting_func(msg)

        elif call.data == 'cancel$':
            pass
    except AttributeError as ae:
        print('Lambda Error:', ae)

###################################################################################################################

# bot.polling(none_stop=True)

if __name__ == "__main__":
    app.run()
