import logging
from datetime import datetime

import requests
from django.conf import settings

from funds.services.dates import to_timestamp
from funds.services.constants import USDT
from funds.models import HistoricalRecord

CRYPTOWATCH_HOST = "https://api.cryptowat.ch"
BINANCE = "binance"

api_key = settings.CRYPTOWATCH_API_KEY
api_secret = settings.CRYPTOWATCH_API_SECRET


def get_open_high_low_close_volume(list) -> HistoricalRecord:
    date = datetime.utcfromtimestamp(list[0])
    open = list[1]
    high = list[2]
    low = list[3]
    close = list[4]
    volume = [6]  # volume in USD, for volume in asset units list[5]
    return HistoricalRecord(date, open, high, low, close, volume)


def get_usdt_close_price_on_date(asset_symbol, date) -> HistoricalRecord:
    pair = f'{asset_symbol}{USDT}'
    url = f'{CRYPTOWATCH_HOST}/markets/{BINANCE}/{pair}/ohlc'
    date_in_unix_timestamp = to_timestamp(date)
    one_day_in_seconds = 86400
    headers = {
        "X-CW-API-Key": api_key
    }
    query_params = {
        "after": date_in_unix_timestamp,
        "before": date_in_unix_timestamp,
        "periods": [one_day_in_seconds],
        "apikey": api_key
    }

    response = requests.get(url, headers=headers, params=query_params)
    if response.status_code != 200:
        logging.error(f'Error getting close price on date for {pair}')
    json = response.json()
    if 'error' in json:
        error_message = f'error: {json["error"]}'
        logging.error(error_message)
        raise LookupError(error_message)

    values_on_date = json['result'][f'{one_day_in_seconds}'][0]
    historical_record = get_open_high_low_close_volume(values_on_date)
    return historical_record.close


def get_pair_close_price_on_date(pair, date) -> HistoricalRecord:
    url = f'{CRYPTOWATCH_HOST}/markets/{BINANCE}/{pair}/ohlc'
    date_in_unix_timestamp = to_timestamp(date)
    one_day_in_seconds = 86400
    query_params = {
        "after": date_in_unix_timestamp,
        "before": date_in_unix_timestamp,
        "periods": [one_day_in_seconds],
    }
    response = requests.get(url, params=query_params)
    if response.status_code != 200:
        logging.error(f'Error getting close price on date for {pair}')
    json = response.json()
    print(f'{response.text}')
    values_on_date = json["result"][f'{one_day_in_seconds}'][0]
    historical_record = get_open_high_low_close_volume(values_on_date)
    return historical_record.close
