# -*- coding: utf-8 -*-

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

import ccxt.async_support
from ccxt.base.types import Balances, Int, Order, OrderBook, Str, Ticker, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List


class cube(ccxt.async_support.cube):

    def describe(self):
        return self.deep_extend(super(cube, self).describe(), {
            'has': {
                'ws': True,
                'watchBalance': False,
                'watchMyTrades': False,
                'watchOHLCV': False,
                'watchOrderBook': True,
                'watchOrders': False,
                'watchTicker': False,
                'watchTrades': False,
            },
            'options': {
                'api': {
                    'ws': {
                        'mendelev': {
                            'public': {
                                'orderbook': '/book/{marketId}',
                                'orderbookTops': '/tops',
                            },
                        },
                        'os': {
                            'private': {
                                'root': '/',
                            },
                        },
                    },
                },
            },
        })

    def get_websocket_url(self, system: str, privacy: str, path: str, params={}):
        environment = self.options['environment']
        path = self.implode_params(path, params)
        return self.urls['api']['ws'][environment][system] + self.options['api']['ws'][environment][privacy][path]

    async def watch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://cubexch.gitbook.io/cube-api/websocket-market-data-api#order-book-data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        meta = await self.fetchMarketMeta(symbol)
        symbol = self.safe_string(meta, 'symbol')
        marketId = self.safe_string(meta, 'marketId')
        # market = self.safe_string(meta, 'market')
        url = self.get_websocket_url('mendelev', 'public', 'orderbook', {'marketId': marketId})
        klines = self.safe_value(params, 'klines', 1)
        request = {
            'mbp': True,
            'mbo': False,
            'trades': True,
            'summary': True,
            'klines': klines,
            'marketsIds': 200047,
        }
        messageHash = ''
        return await self.watch(url, messageHash, request, messageHash)

    def handle_order_book(self, client: Client, message):

        pass

    async def watch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        return None

    def handle_ticker(self, client: Client, message):

        pass

    async def watch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        url = self.get_websocket_url('mendelev', 'public', 'orderbook')
        # await self.authenticate(url)
        await self.load_markets()
        market = self.market(symbol)
        symbol = market['symbol']
        messageHash = 'ohlcv:' + symbol   # ???
        request = {}
        ohlcv = await self.watch(url, messageHash, self.extend(request, params), messageHash)
        if self.newUpdates:
            limit = ohlcv.getLimit(symbol, limit)
        return self.filter_by_since_limit(ohlcv, since, limit, 0, True)

    def handle_ohlcv(self, client: Client, message):
        #
        #    {
        #        "endtime": 1714423464,
        #        "interval": "15m",
        #        "limit": 1000,
        #        "marketId": 200047,
        #        "startTime": 1714122864,
        #    }
        #
        marketId = self.safe_string(message, 'marketId')
        symbol = self.safe_symbol(marketId)
        data = {}
        interval = self.safe_string(data, 'interval')
        request = {
            symbol,
            interval,
        }
        return request

    async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made in a market
        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure
        """
        return None

    def handle_trades(self, client: Client, message):

        pass

    async def watch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        watches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure
        """
        return None

    def handle_order(self, client: Client, message):

        pass

    async def watch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made by the user
        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unifiedMargin]: use unified margin account
        :returns dict[]: a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure
        """
        return None

    async def watch_balance(self, params={}) -> Balances:
        """
        watch balance and get the amount of funds available for trading or funds locked in orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.portfolioMargin]: set to True if you would like to watch the balance of a portfolio margin account
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        return None
