import json
import os
import time
import traceback

import pytz
import requests
from anticaptchaofficial.imagecaptcha import imagecaptcha
from django.core.cache import caches
from django.db import close_old_connections, connection
from django.utils import timezone
from django_redis import get_redis_connection

from accounts.models import FifaAccountLog, FifaAccount, TelegramMessage
from futplus.settings import BASE_DIR
from utils.models import SystemLog

# print_cache = caches['print_log']
print_cache2 = get_redis_connection('print_log')
if os.name == 'nt':
    import diskcache
    console_worker_cache = diskcache.Cache(os.path.join(BASE_DIR, '.data/console_worker_info'))
else:
    console_worker_cache = caches['diskcache_alternative']

def new_print(fifa_account: FifaAccount, *args, **kwargs):
    bulk_list = kwargs.get('bulk_list', [])
    if bulk_list and (isinstance(bulk_list, tuple) or isinstance(bulk_list, list)):
        objs = []
        for item in bulk_list:
            text = ''
            if isinstance(item, list) or isinstance(item, tuple):
                for i in item:
                    text += str(i) + ' '
            else:
                text += str(item) + ' '
            objs.append(FifaAccountLog(fifa_account_id=fifa_account.id, description=text))
        FifaAccountLog.objects.using('logs_pgbouncer').bulk_create(objs=objs)

    else:
        text = ''
        for i in args:
            text += str(i) + ' '
        for key, value in kwargs.items():
            text += str(key) + ' : ' + str(value) + ' '
        # FifaAccountLog.objects.using('logs').create(fifa_account_id=fifa_account.id, description=text)
        # print_cache.set(
        #     f'print_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime()})
        try:
            print_cache2.rpush('print_log2', json.dumps(
                {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            ))
        except Exception as save_error:
            print('cant save logs : ', json.dumps(
                {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            ), ' error : ', save_error)
            # print_cache2.rpush('print_log2', json.dumps(
            #     {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            # ))


def save_account_request(fifa_account: FifaAccount, link: str, create_time=None):
    if not create_time:
        # print_cache.set(
        #     f'request_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': timezone.localtime()})

        # FifaAccountRequest.objects.using('logs').create(
        #     fifa_account=fifa_account,
        #     link=link,
        # )
        save_time = timezone.localtime().isoformat()
        # print_cache2.rpush('request_log2', json.dumps(
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': timezone.localtime().isoformat()}
        # ))
    else:
        # print_cache.set(
        #     f'request_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': create_time})
        # FifaAccountRequest.objects.using('logs').create(
        #     fifa_account=fifa_account,
        #     link=link,
        #     create_time=create_time,
        # )
        save_time = create_time.isoformat()
        # print_cache2.rpush('request_log2', json.dumps(
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': create_time.isoformat()}
        # ))
    try:
        print_cache2.rpush('request_log2', json.dumps(
            {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': save_time}
        ))
    except:
        print('cant save requests : ', json.dumps(
            {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': save_time}
        ))


def sys_log_save(worker_name: str, *args, **kwargs):
    bulk_list = kwargs.get('bulk_list', [])
    if bulk_list and (isinstance(bulk_list, tuple) or isinstance(bulk_list, list)):
        objs = []
        for item in bulk_list:
            text = ''
            if isinstance(item, list) or isinstance(item, tuple):
                for i in item:
                    text += str(i) + ' '
            else:
                text += str(item) + ' '
            objs.append(SystemLog(worker_name=worker_name, description=text))
        SystemLog.objects.bulk_create(objs=objs)

    else:
        text = ''
        for i in args:
            text += str(i) + ' '
        for key, value in kwargs.items():
            text += str(key) + ' : ' + str(value) + ' '
        SystemLog.objects.create(worker_name=worker_name, description=text)


def anticaptcha_text_captcha(captcha_image):
    solver = imagecaptcha()
    solver.set_verbose(1)
    solver.set_key("da2bf9e50b0d7e75a7c723a5d7b60f1a")

    # Specify softId to earn 10% commission with your app.
    # Get your softId here: https://anti-captcha.com/clients/tools/devcenter
    solver.set_soft_id(0)

    captcha_text = solver.solve_and_return_solution(captcha_image)
    if captcha_text != 0:
        return {'status_bool': True, 'status': 'success', 'captcha_text': captcha_text}
    else:
        return {'status_bool': False, 'status': 'failed', 'error': str(solver.error_code)}


def telegram_send_message_fifa_account(fifa_account, bot_token, text, chat_id, message_thread_id=None, message_type=None):
    close_old_connections()
    TelegramMessage.objects.create(
        fifa_account=fifa_account,
        message_type=message_type,
        text=text
    )
    try:
        return telegram_send_message(bot_token, text, chat_id, message_thread_id)
    except:
        new_print(fifa_account, 'cant send telegram message , ', traceback.format_exc())
        return


def telegram_send_message(bot_token, text, chat_id, message_thread_id=None):
    url = f'https://api.telegram.org/bot{bot_token}/sendMessage'
    params = {
        'chat_id': chat_id,
        'text': text,
    }
    if message_thread_id:
        params.update({'message_thread_id': message_thread_id})
    result = requests.get(url, params=params)
    return result


def get_db_time(timezone_=None):
    if not timezone_:
        timezone_ = 'UTC'
    with connection.cursor() as cursor:
        cursor.execute("SELECT TIMEZONE(%s, NOW());", [timezone_])
        row = cursor.fetchone()
    return row[0]
