# -*- 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.async_support.base.ws.cache import ArrayCache
from ccxt.base.types import Int, OrderBook, Strings, Ticker, Tickers, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List
from ccxt.base.errors import ExchangeError


class bithumb(ccxt.async_support.bithumb):

    def describe(self):
        return self.deep_extend(super(bithumb, self).describe(), {
            'has': {
                'ws': True,
                'watchBalance': False,
                'watchTicker': True,
                'watchTickers': True,
                'watchTrades': True,
                'watchOrderBook': True,
                'watchOHLCV': False,
            },
            'urls': {
                'api': {
                    'ws': 'wss://pubwss.bithumb.com/pub/ws',
                },
            },
            'options': {},
            'streaming': {},
            'exceptions': {},
        })

    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
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://github.com/ccxt/ccxt/wiki/Manual#ticker-structure>`
        """
        url = self.urls['api']['ws']
        await self.load_markets()
        market = self.market(symbol)
        messageHash = 'ticker:' + market['symbol']
        request = {
            'type': 'ticker',
            'symbols': [market['base'] + '_' + market['quote']],
            'tickTypes': [self.safe_string(params, 'tickTypes', '24H')],
        }
        return await self.watch(url, messageHash, self.extend(request, params), messageHash)

    async def watch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :param str[] symbols: 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>`
        """
        await self.load_markets()
        url = self.urls['api']['ws']
        marketIds = []
        messageHashes = []
        symbols = self.market_symbols(symbols, None, False, True, True)
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            market = self.market(symbol)
            marketIds.append(market['base'] + '_' + market['quote'])
            messageHashes.append('ticker:' + market['symbol'])
        request = {
            'type': 'ticker',
            'symbols': marketIds,
            'tickTypes': [self.safe_string(params, 'tickTypes', '24H')],
        }
        message = self.extend(request, params)
        newTicker = await self.watch_multiple(url, messageHashes, message, messageHashes)
        if self.newUpdates:
            result = {}
            result[newTicker['symbol']] = newTicker
            return result
        return self.filter_by_array(self.tickers, 'symbol', symbols)

    def handle_ticker(self, client: Client, message):
        #
        #    {
        #        "type" : "ticker",
        #        "content" : {
        #            "symbol" : "BTC_KRW",           # 통화코드
        #            "tickType" : "24H",                 # 변동 기준시간- 30M, 1H, 12H, 24H, MID
        #            "date" : "20200129",                # 일자
        #            "time" : "121844",                  # 시간
        #            "openPrice" : "2302",               # 시가
        #            "closePrice" : "2317",              # 종가
        #            "lowPrice" : "2272",                # 저가
        #            "highPrice" : "2344",               # 고가
        #            "value" : "2831915078.07065789",    # 누적거래금액
        #            "volume" : "1222314.51355788",  # 누적거래량
        #            "sellVolume" : "760129.34079004",   # 매도누적거래량
        #            "buyVolume" : "462185.17276784",    # 매수누적거래량
        #            "prevClosePrice" : "2326",          # 전일종가
        #            "chgRate" : "0.65",                 # 변동률
        #            "chgAmt" : "15",                    # 변동금액
        #            "volumePower" : "60.80"         # 체결강도
        #        }
        #    }
        #
        content = self.safe_dict(message, 'content', {})
        marketId = self.safe_string(content, 'symbol')
        symbol = self.safe_symbol(marketId, None, '_')
        ticker = self.parse_ws_ticker(content)
        messageHash = 'ticker:' + symbol
        self.tickers[symbol] = ticker
        client.resolve(self.tickers[symbol], messageHash)

    def parse_ws_ticker(self, ticker, market=None):
        #
        #    {
        #        "symbol" : "BTC_KRW",           # 통화코드
        #        "tickType" : "24H",                 # 변동 기준시간- 30M, 1H, 12H, 24H, MID
        #        "date" : "20200129",                # 일자
        #        "time" : "121844",                  # 시간
        #        "openPrice" : "2302",               # 시가
        #        "closePrice" : "2317",              # 종가
        #        "lowPrice" : "2272",                # 저가
        #        "highPrice" : "2344",               # 고가
        #        "value" : "2831915078.07065789",    # 누적거래금액
        #        "volume" : "1222314.51355788",  # 누적거래량
        #        "sellVolume" : "760129.34079004",   # 매도누적거래량
        #        "buyVolume" : "462185.17276784",    # 매수누적거래량
        #        "prevClosePrice" : "2326",          # 전일종가
        #        "chgRate" : "0.65",                 # 변동률
        #        "chgAmt" : "15",                    # 변동금액
        #        "volumePower" : "60.80"         # 체결강도
        #    }
        #
        date = self.safe_string(ticker, 'date', '')
        time = self.safe_string(ticker, 'time', '')
        datetime = date[0:4] + '-' + date[4:6] + '-' + date[6:8] + 'T' + time[0:2] + ':' + time[2:4] + ':' + time[4:6]
        marketId = self.safe_string(ticker, 'symbol')
        return self.safe_ticker({
            'symbol': self.safe_symbol(marketId, market, '_'),
            'timestamp': self.parse8601(datetime),
            'datetime': datetime,
            'high': self.safe_string(ticker, 'highPrice'),
            'low': self.safe_string(ticker, 'lowPrice'),
            'bid': None,
            'bidVolume': self.safe_string(ticker, 'buyVolume'),
            'ask': None,
            'askVolume': self.safe_string(ticker, 'sellVolume'),
            'vwap': None,
            'open': self.safe_string(ticker, 'openPrice'),
            'close': self.safe_string(ticker, 'closePrice'),
            'last': None,
            'previousClose': self.safe_string(ticker, 'prevClosePrice'),
            'change': self.safe_string(ticker, 'chgAmt'),
            'percentage': self.safe_string(ticker, 'chgRate'),
            'average': None,
            'baseVolume': self.safe_string(ticker, 'volume'),
            'quoteVolume': self.safe_string(ticker, 'value'),
            'info': ticker,
        }, market)

    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
        :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://github.com/ccxt/ccxt/wiki/Manual#order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        url = self.urls['api']['ws']
        market = self.market(symbol)
        symbol = market['symbol']
        messageHash = 'orderbook' + ':' + symbol
        request = {
            'type': 'orderbookdepth',
            'symbols': [market['base'] + '_' + market['quote']],
        }
        orderbook = await self.watch(url, messageHash, self.extend(request, params), messageHash)
        return orderbook.limit()

    def handle_order_book(self, client: Client, message):
        #
        #    {
        #        "type" : "orderbookdepth",
        #            "content" : {
        #            "list" : [
        #                {
        #                    "symbol" : "BTC_KRW",
        #                    "orderType" : "ask",        # 주문타입 – bid / ask
        #                    "price" : "10593000",       # 호가
        #                    "quantity" : "1.11223318",  # 잔량
        #                    "total" : "3"               # 건수
        #                },
        #                {"symbol" : "BTC_KRW", "orderType" : "ask", "price" : "10596000", "quantity" : "0.5495", "total" : "8"},
        #                {"symbol" : "BTC_KRW", "orderType" : "ask", "price" : "10598000", "quantity" : "18.2085", "total" : "10"},
        #                {"symbol" : "BTC_KRW", "orderType" : "bid", "price" : "10532000", "quantity" : "0", "total" : "0"},
        #                {"symbol" : "BTC_KRW", "orderType" : "bid", "price" : "10572000", "quantity" : "2.3324", "total" : "4"},
        #                {"symbol" : "BTC_KRW", "orderType" : "bid", "price" : "10571000", "quantity" : "1.469", "total" : "3"},
        #                {"symbol" : "BTC_KRW", "orderType" : "bid", "price" : "10569000", "quantity" : "0.5152", "total" : "2"}
        #            ],
        #            "datetime":1580268255864325     # 일시
        #        }
        #    }
        #
        content = self.safe_dict(message, 'content', {})
        list = self.safe_list(content, 'list', [])
        first = self.safe_dict(list, 0, {})
        marketId = self.safe_string(first, 'symbol')
        symbol = self.safe_symbol(marketId, None, '_')
        timestampStr = self.safe_string(content, 'datetime')
        timestamp = self.parse_to_int(timestampStr[0:13])
        if not (symbol in self.orderbooks):
            ob = self.order_book()
            ob['symbol'] = symbol
            self.orderbooks[symbol] = ob
        orderbook = self.orderbooks[symbol]
        self.handle_deltas(orderbook, list)
        orderbook['timestamp'] = timestamp
        orderbook['datetime'] = self.iso8601(timestamp)
        messageHash = 'orderbook' + ':' + symbol
        client.resolve(orderbook, messageHash)

    def handle_delta(self, orderbook, delta):
        #
        #    {
        #        symbol: "ETH_BTC",
        #        orderType: "bid",
        #        price: "0.07349517",
        #        quantity: "0",
        #        total: "0",
        #    }
        #
        sideId = self.safe_string(delta, 'orderType')
        side = 'bids' if (sideId == 'bid') else 'asks'
        bidAsk = self.parse_bid_ask(delta, 'price', 'quantity')
        orderbookSide = orderbook[side]
        orderbookSide.storeArray(bidAsk)

    def handle_deltas(self, orderbook, deltas):
        for i in range(0, len(deltas)):
            self.handle_delta(orderbook, deltas[i])

    async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://github.com/ccxt/ccxt/wiki/Manual#public-trades>`
        """
        await self.load_markets()
        url = self.urls['api']['ws']
        market = self.market(symbol)
        symbol = market['symbol']
        messageHash = 'trade:' + symbol
        request = {
            'type': 'transaction',
            'symbols': [market['base'] + '_' + market['quote']],
        }
        trades = await self.watch(url, messageHash, self.extend(request, params), messageHash)
        if self.newUpdates:
            limit = trades.getLimit(symbol, limit)
        return self.filter_by_since_limit(trades, since, limit, 'timestamp', True)

    def handle_trades(self, client, message):
        #
        #    {
        #        "type" : "transaction",
        #        "content" : {
        #            "list" : [
        #                {
        #                    "symbol" : "BTC_KRW",
        #                    "buySellGb" : "1",
        #                    "contPrice" : "10579000",
        #                    "contQty" : "0.01",
        #                    "contAmt" : "105790.00",
        #                    "contDtm" : "2020-01-29 12:24:18.830039",
        #                    "updn" : "dn"
        #                }
        #            ]
        #        }
        #    }
        #
        content = self.safe_dict(message, 'content', {})
        rawTrades = self.safe_list(content, 'list', [])
        for i in range(0, len(rawTrades)):
            rawTrade = rawTrades[i]
            marketId = self.safe_string(rawTrade, 'symbol')
            symbol = self.safe_symbol(marketId, None, '_')
            if not (symbol in self.trades):
                limit = self.safe_integer(self.options, 'tradesLimit', 1000)
                stored = ArrayCache(limit)
                self.trades[symbol] = stored
            trades = self.trades[symbol]
            parsed = self.parse_ws_trade(rawTrade)
            trades.append(parsed)
            messageHash = 'trade' + ':' + symbol
            client.resolve(trades, messageHash)

    def parse_ws_trade(self, trade, market=None):
        #
        #    {
        #        "symbol" : "BTC_KRW",
        #        "buySellGb" : "1",
        #        "contPrice" : "10579000",
        #        "contQty" : "0.01",
        #        "contAmt" : "105790.00",
        #        "contDtm" : "2020-01-29 12:24:18.830039",
        #        "updn" : "dn"
        #    }
        #
        marketId = self.safe_string(trade, 'symbol')
        datetime = self.safe_string(trade, 'contDtm')
        sideId = self.safe_string(trade, 'buySellGb')
        return self.safe_trade({
            'id': None,
            'info': trade,
            'timestamp': self.parse8601(datetime),
            'datetime': datetime,
            'symbol': self.safe_symbol(marketId, market, '_'),
            'order': None,
            'type': None,
            'side': 'buy' if (sideId == '1') else 'sell',
            'takerOrMaker': None,
            'price': self.safe_string(trade, 'contPrice'),
            'amount': self.safe_string(trade, 'contQty'),
            'cost': self.safe_string(trade, 'contAmt'),
            'fee': None,
        }, market)

    def handle_error_message(self, client: Client, message):
        #
        #    {
        #        "status" : "5100",
        #        "resmsg" : "Invalid Filter Syntax"
        #    }
        #
        if not ('status' in message):
            return True
        errorCode = self.safe_string(message, 'status')
        try:
            if errorCode != '0000':
                msg = self.safe_string(message, 'resmsg')
                raise ExchangeError(self.id + ' ' + msg)
            return True
        except Exception as e:
            client.reject(e)
        return True

    def handle_message(self, client: Client, message):
        if not self.handle_error_message(client, message):
            return
        topic = self.safe_string(message, 'type')
        if topic is not None:
            methods = {
                'ticker': self.handle_ticker,
                'orderbookdepth': self.handle_order_book,
                'transaction': self.handle_trades,
            }
            method = self.safe_value(methods, topic)
            if method is not None:
                method(client, message)
