import logging
import json
import requests


from algo.config import config

log = logging.getLogger(__name__)


class TrainerApi:
    def __init__(self) -> None:
        self._url = config.trainer_url
        self._token = config.trainer_token
        self._trainer_name = config.trainer_name
        self._last_report = None

    def _is_configured(self):
        return self._url is not None

    def _report_transaction(self, trader_id, transaction: str,  price: float, units: int, details:  dict):
        try:
            res = requests.post(
                f'{self._url}/api/orders/',
                data={
                    'trader': trader_id,
                    'transaction': transaction,
                    'price': price,
                    'units': units,
                    'details':  json.dumps(details)
                },
                timeout=1.0,
                headers={'Authorization': f'Token {self._token}'}
            )
            log.info('reporting-transaction', extra={'res': res.status_code, 'transaction': transaction})
        except Exception as exc:  # pylint: disable=broad-except
            log.error('error-reporting-transaction', exc_info=exc, extra={'transaction': transaction, 'exc': exc})

    def _report_state(self, trader_id:  str, total: float,  total_pips: float,  extra_data:  dict):
        try:
            res = requests.put(
                f'{self._url}/api/positions/{trader_id}/',
                data={
                    'total': total,
                    'total_pips': total_pips,
                    'target_data':  json.dumps(extra_data)
                },
                timeout=1.0,
                headers={'Authorization': f'Token {self._token}'}
            )
            log.info('reporting', extra={'res': res.status_code, 'total': total})
        except Exception as exc:  # pylint: disable=broad-except
            log.error('error-reporting-state', exc_info=exc, extra={'exc': exc})

    def report_state(self, total: float,  total_pips: float,  extra_data:  dict):
        if self._is_configured():
            self._report_state(self._trainer_name, total, total_pips, extra_data)

    def report_transaction(self, transaction: str,  price: float, units: int, details:  dict):
        if self._is_configured():
            self._report_transaction(self._trainer_name, transaction, price, units, details)
