﻿  #!C:\Python\Python311\python.exe
# -*- coding: utf-8 -*-
# cl_man_regist.py  03-10-202318:11
 
import sys
import re
import datetime
from collections import abc
import requests
import json

import platform
import asyncio
# try:
#     from aiogram import Bot
#
# except Exception as inst:
#     print("Exception aiogram import Bot")  # the exception type
#     print(type(inst))  # the exception type
#     print(inst.args)  # arguments stored in .args
#     print(inst)  # __str__ allows args to be printed directly,    
#     pass
 
from core.settings import settings

import threading

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # print("Windows WindowsWindows Windows Windows ")
    s = "H:\\colect\\biblioteka\\programs\\LiClipse 10.0.0\\LiClipse Workspace\\Telegram_ESP32WebApp\\"
    # s2 = "H:\\colect\\biblioteka\\programs\\LiClipse 10.0.0\\LiClipse Workspace\\Telegram_ESP32WebApp\\man_db\\"
    pass
else:
    # print("Linux  Linux Linux Linux Linux Linux  ") 
    # sys.path.insert(0, '/opt/Telegram_ESP32/')  # todo
    s = '/opt/Telegram_ESP32/'
    pass           

sys.path.insert(0, s)
# sys.path.insert(0, s2)
sys.path.insert(0, '../..')
sys.path.insert(0, '..')
sys.path.insert(0, '*')

from utils.consts import clC

from man_db.MDB import  clMDB
from man_db.clManTEMP_DB import  clManTEMP_DB
from man_db.clManTZone_DB import  clManTZone_DB
from man_db.clManEmail_DB import  clManEmail_DB

from man_db.MDB import   clMLog
from man_db.clMan_key_sec_DB import   clMan_key_sec_DB 

v_clMan_key_sec_DB = clMan_key_sec_DB()

v_clManTEMP_DB = clManTEMP_DB()
v_clManTZone_DB = clManTZone_DB()
v_clManEmail_DB = clManEmail_DB()
v_clMLog = clMLog()
 
from .cl_man_grafana import   cl_man_grafana

v_clMDB = clMDB()


class cl_man_regist(object):
    '''    
 
    '''
 
    dict_v = {}

    def __init__(self):
        pass


    @staticmethod
    def makeFinalMess(new_user):
        return (clC.g("mess_registFinal") % (new_user["name"],new_user['password'],clC.url_server_grafana,clC.url_server_grafana))
 
    @staticmethod
    def registration_reg_data(request_data):  # 16-09-202312:59
        new_user = cl_man_grafana.reg_user(
            request_data['username'], request_data['useremail'])
        if new_user == 0:
            return clC.v_error
        else:
            one = v_clMan_key_sec_DB.get_datasec(request_data['key_sec'])

            id_user_grafana = new_user["id"]
            if id_user_grafana > 0:
                id_user = v_clMDB.INSERTuser(request_data['username'],
                      one['login_telegram'] , one['id_telegram'], id_user_grafana)
                if id_user > 0:
                    Mess=cl_man_regist.makeFinalMess(new_user)
                    cl_man_regist.send_message(one['id_telegram'], Mess)
                    return 0
            else:
                return clC.v_error    
            # is_useremail=cl_man_grafana.get_userByEmail(useremail)
            return clC.v_error   

    @staticmethod
    def check_key_sec(key_sec, deb=False):  # 16-09-202312:59
        ans = v_clMan_key_sec_DB.is_key_sec(key_sec, deb)
        return ans  # {"id": ,"id_telegram": }

    @staticmethod
    def check_reg_useremail(useremail):  # 16-09-202312:59
        is_useremail = cl_man_grafana.get_userByEmail(useremail)
        return is_useremail

    @staticmethod
    async def send_messageW(id_telegram, message):
        from aiogram import Bot
        from aiogram.types import ReplyKeyboardRemove

        print(platform.system())
        bot:Bot = 0
        if platform.system() == "Windows":
            #print("Windows WindowsWindows Windows Windows ")
            # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
            bot = Bot(settings.bots.bot_token_win)
        else:
            print("Linux  Linux Linux Linux Linux Linux  ")
            bot = Bot(settings.bots.bot_token)
        await bot.send_message(id_telegram, message,
                                reply_markup=ReplyKeyboardRemove()
       )  
        await bot.session.close()     
    
        print("main END  ")
    
    @staticmethod
    def send_message(id_telegram, message):
        # id_telegram= 960419151
        print("send_message ")

        # loop = asyncio.get_event_loop()
        # loop.run_until_complete(cl_man_regist.send_messageW(id_telegram,message))
        # loop.close()
        def my_thread_function(id_telegram, message, bot_token_win, bot_token):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
        
            async def my_async_function(id_telegram, message, bot_token_win, bot_token):
                try:
                    from aiogram import Bot
                    from aiogram.types import ReplyKeyboardRemove

                    bot:Bot = 0
                    if platform.system() == "Windows":
                        print("my_async_function WindowsWindows Windows Windows ")
                        # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
                        bot = Bot(bot_token_win)
                    else:
                        print("my_async_function  Linux Linux Linux Linux Linux  ")
                        bot = Bot(bot_token)
                    await bot.send_message(id_telegram, message ,
                                            reply_markup=ReplyKeyboardRemove() , parse_mode="HTML"
                   )  
                    await bot.session.close()     
                    print("my_async_function END  ")
                except Exception as inst:
                    print("Exception my_async_function")  # the exception type
                    print(type(inst))  # the exception type
                    print(inst.args)  # arguments stored in .args
                    print(inst)  # __str__ allows args to be printed directly,    
                    pass

            loop.run_until_complete(my_async_function(id_telegram, message, bot_token_win, bot_token))
                
        my_thread = threading.Thread(target=lambda: my_thread_function(
            id_telegram,
            message,
            settings.bots.bot_token_win,
            settings.bots.bot_token 
            )).start()

# my_thread = threading.Thread(target=lambda: my_thread_function(id_telegram,message)).start()
# my_thread = threading.Thread(target=my_thread_function)
# my_thread.start()

# def my_thread_function():
#     loop = asyncio.new_event_loop()
#     asyncio.set_event_loop(loop)
#
#     async def my_async_function():
#         # Your async code here
#
#     loop.run_until_complete(my_async_function())
#
# my_thread = threading.Thread(target=my_thread_function)
# my_thread.start()
 
