import requests
import json
from datetime import datetime, timedelta
from BaseModels.mailSender import techSendMail
from GeneralApp.temp_data_funcs import *


def get_nbrb_currency_id_by_currency_code(code):
    data = requests.get('https://www.nbrb.by/api/exrates/currencies')

    json_data = json.loads(data.content)

    for item in json_data:
        if 'Cur_Abbreviation' in item and item['Cur_Abbreviation'] == code:
            return item['Cur_Code']

    return None


def get_nbrb_rate_by_currency_code(code, date=None):
    # if code == 'BYN':
    #     return 1
    #
    # tmp_rec = get_tmp_data('currency_rate', code)
    # if tmp_rec and tmp_rec.json_data:
    #     # если с момента последнего импорта прошло меньше 30 минут - забираем курс из базы
    #     if datetime.strptime(tmp_rec.json_data['DT'], '%d.%m.%Y %H:%M') + timedelta(minutes=30) > datetime.now():
    #         return tmp_rec.json_data['rate']

    # currency_id = get_nbrb_currency_id_by_currency_code('USD')
    rate = None
    res = None
    req_str = None

    try:

        msg = f'get_nbrb_rate_by_currency_code'
        print(msg)

        if not date:
            # data = requests.get('https://www.nbrb.by/API/ExRates/Rates/{0}?Periodicity=0'.format(str(currency_id)))
            req_str = 'https://www.nbrb.by/api/exrates/rates/{0}?parammode=2'.format(str(code))
        else:
            date_str = datetime.now().strftime('%Y-%m-%d')
            date_str = date_str.replace('-0', '-')
            req_str = 'https://www.nbrb.by/api/exrates/rates/{0}?parammode=2&ondate={1}'.format(
                str(code),
                date_str
            )
        e = None
        try:
            msg = f'GET {req_str}'
            print(msg)
            res = requests.get(req_str, timeout=3)
            msg = f'answer received = {str(res)}'
            print(msg)
        except Exception as e:
            msg = f'Exception GET {req_str} = {str(e)} ({str(res)})'
            print(msg)
            res = None

        if not res and res != 200:
            # if tmp_rec:
            #     rate = tmp_rec.json_data['rate']
            # else:
            #     rate_Dict = {
            #         'rate': 1,
            #         'DT': datetime.now().strftime('%d.%m.%Y %H:%M')
            #     }
            #     create_or_update_tmp_data('currency_rate', code, rate_Dict)
            #     rate = 1

            msg = '<b style="color : red;">!!!!! --- get_nbrb_rate_by_currency_code requests GET error={0}</b><br>{1}<br>{2}<br>rate set = {3}'.format(
                str(e),
                str(res),
                str(req_str),
                str(rate)
            )
            print(msg)
            techSendMail(msg, 'tE get_nbrb_rate_by_currency_code error')

        data = json.loads(res.content)

        if data and 'Cur_OfficialRate' in data and 'Cur_Scale' in data:
            rate = data['Cur_OfficialRate'] / data['Cur_Scale']

            rate_Dict = {
                'rate': rate,
                'DT': datetime.now().strftime('%d.%m.%Y %H:%M')
            }

            create_or_update_tmp_data('currency_rate', code, rate_Dict)

    except Exception as e:
        msg = '<b style="color : red;">!!!!! --- get_nbrb_rate_by_currency_code error={0}</b><br>{1}<br>{2}'.format(
            str(e),
            str(res),
            str(req_str)
        )
        print(msg)
        techSendMail(msg, 'tE get_nbrb_rate_by_currency_code error')

        # if not res:
        #     rate_Dict = {
        #         'rate': 1,
        #         'DT': datetime.now().strftime('%d.%m.%Y %H:%M')
        #     }
        #     create_or_update_tmp_data('currency_rate', code, rate_Dict)
        #     return 1

    if rate:
        msg = f'get nbrb nb rate = {rate}'
        print(msg)

    return rate
