# -*- 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

from ccxt.async_support.base.exchange import Exchange
import hashlib
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import DECIMAL_PLACES


class vinex(Exchange):

    def describe(self):
        return self.deep_extend(super(vinex, self).describe(), {
            'id': 'vinex',
            'name': 'Vinex Network',
            'countries': ['VG'],
            'version': 'v2',
            'rateLimit': 500,
            'has': {
                'CORS': False,
                'createMarketOrder': True,
                'fetchClosedOrders': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
            },
            'timeframes': {
                '1m': '1m',
                '5m': '5m',
                '30m': '30m',
                '1h': '1h',
                '4h': '4h',
                '1d': '1d',
            },
            'hostname': 'vinex.network',
            'urls': {
                'logo': 'https://storage.googleapis.com/vinex-images/mail-icons/vinex-logo.png',
                'api': 'https://api.vinex.network/api/v2',
                'www': 'https://vinex.network/',
                'doc': 'https://docs.vinex.network/',
                'fees': 'https://vinex.network/fee',
                'referral': 'https://vinex.network/?ref=SJW2h3',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{marketId}',
                        'get-ticker',
                        'get-order-book',
                        'get-market-history',
                        'candles',
                    ],
                },
                'private': {
                    'get': [
                        'balances',
                        'get-my-orders',
                        'get-my-trading',
                    ],
                    'post': [
                        'place-order',
                        'cancel-order',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'maker': 0.0025,
                    'taker': 0.0025,
                },
            },
            'options': {
                'symbolSeparator': '_',
            },
        })

    def cost_to_precision(self, symbol, cost):
        return self.decimal_to_precision(cost, TRUNCATE, self.markets[symbol]['precision']['price'], DECIMAL_PLACES)

    def fee_to_precision(self, symbol, fee):
        return self.decimal_to_precision(fee, TRUNCATE, self.markets[symbol]['precision']['price'], DECIMAL_PLACES)

    def parse_symbol(self, id):
        [quoteId, baseId] = id.split(self.options['symbolSeparator'])
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        return base + '/' + quote

    async def fetch_markets(self, params={}):
        markets = await self.publicGetMarkets(params)
        # [
        #     {
        #         "symbol": "BTC_ETH",
        #         "lastPrice": 0.025897,
        #         "volume": 4.64849624,
        #         "change24h": -0.01265775,
        #         "high24h": 0.026341,
        #         "low24h": 0.02577,
        #         "decPrice": 6,
        #         "decAmount": 4,
        #         "status": True
        #     },
        #     {
        #         "symbol": "ETH_MAS",
        #         "lastPrice": 0.00000888,
        #         "volume": 1.536,
        #         "change24h": 0,
        #         "high24h": 0,
        #         "low24h": 0,
        #         "decPrice": 8,
        #         "decAmount": 4,
        #         "threshold": 0.001,
        #         "status": True
        #     }
        # ]
        result = []
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'symbol')
            [quoteId, baseId] = id.split(self.options['symbolSeparator'])
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            symbol = base + '/' + quote
            amountPrecision = self.safe_integer(market, 'decAmount', 8)
            pricePrecision = self.safe_integer(market, 'decPrice', 8)
            precision = {
                'amount': amountPrecision,
                'price': pricePrecision,
            }
            status = self.safe_value(market, 'status')
            active = status
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': active,
                'info': market,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': math.pow(10, -precision['price']),
                        # 'min': self.safe_float(market, 'threshold'),
                        'max': None,
                    },
                    'price': {
                        'min': math.pow(10, -precision['price']),
                        'max': None,
                    },
                },
            })
        return result

    def parse_ticker(self, ticker, market=None):
        # {
        #     "timestamp": 1594810517000,
        #     "symbol": "USDT_BTC",
        #     "lastPrice": 9243.4,
        #     "highPrice": 9275.69,
        #     "lowPrice": 9144.28,
        #     "volume": 87188.02735616,
        #     "quoteVolume": 87188.02735616,
        #     "baseVolume": 9.451877,
        #     "change24h": 0.00831004,
        #     "threshold": 5,
        #     "bidPrice": 9206.36,
        #     "askPrice": 9271.2
        # }
        timestamp = self.milliseconds()
        symbol = None
        if market is not None:
            symbol = market['symbol']
        else:
            marketId = self.safe_string(ticker, 'symbol')
            symbol = self.parse_symbol(marketId)
        previous = self.safe_float(ticker, 'PrevDay')
        last = self.safe_float(ticker, 'lastPrice')
        percentage = self.safe_float(ticker, 'change24h')
        change = last * (1 - 1 / (1 + percentage))
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_float(ticker, 'highPrice'),
            'low': self.safe_float(ticker, 'lowPrice'),
            'bid': self.safe_float(ticker, 'bidPrice'),
            'bidVolume': None,
            'ask': self.safe_float(ticker, 'askPrice'),
            'askVolume': None,
            'vwap': None,
            'open': previous,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': self.safe_float(ticker, 'baseVolume'),
            'quoteVolume': self.safe_float(ticker, 'quoteVolume'),
            'info': ticker,
        }

    async def fetch_ticker(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
        }
        ticker = await self.publicGetGetTicker(self.extend(request, params))
        # {
        #     "symbol": "USDT_BTC",
        #     "lastPrice": 9243.4,
        #     "highPrice": 9275.69,
        #     "lowPrice": 9144.28,
        #     "volume": 87188.02735616,
        #     "quoteVolume": 87188.02735616,
        #     "baseVolume": 9.451877,
        #     "change24h": 0.00831004,
        #     "threshold": 5,
        #     "bidPrice": 9206.36,
        #     "askPrice": 9271.2
        # }
        return self.parse_ticker(ticker, market)

    async def fetch_order_book(self, symbol, limit=20, params={}):
        await self.load_markets()
        request = {
            'market': self.market_id(symbol),
            'limit': limit,
        }
        orderbook = await self.publicGetGetOrderBook(self.extend(request, params))
        timestamp = self.milliseconds()
        return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'quantity')

    def parse_trade(self, trade, market=None):
        timestamp = trade['createdAt'] * 1000
        id = self.safe_string(trade, 'id')
        symbol = None
        if market is not None:
            symbol = market['symbol']
        price = self.safe_float(trade, 'price')
        amount = self.safe_float(trade, 'amount')
        cost = None
        if amount is not None:
            if price is not None:
                cost = price * amount
        side = None
        if trade['actionType'] == 1:
            side = 'buy'
        elif trade['actionType'] == 0:
            side = 'sell'
        return {
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'id': id,
            'order': None,
            'type': 'limit',
            'takerOrMaker': None,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': None,
            'info': trade,
        }

    async def fetch_trades(self, symbol, since=None, limit=20, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
            'limit': limit,
        }
        trades = await self.publicGetGetMarketHistory(self.extend(request, params))
        return self.parse_trades(trades, market, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        # {
        #     "timestamp": 1557792000,
        #     "open": 169.58,
        #     "close": 169.58,
        #     "hight": 169.58,
        #     "low": 169.58,
        #     "volume": 5.0874         # in quote
        # }
        return [
            self.safe_integer(ohlcv, 'timestamp') * 1000,
            self.safe_float(ohlcv, 'open'),
            self.safe_float(ohlcv, 'high'),
            self.safe_float(ohlcv, 'low'),
            self.safe_float(ohlcv, 'close'),
            None,
        ]

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'interval': self.timeframes[timeframe],
        }
        if since:
            request['startTime'] = int(math.floor(since / 1000))
        candles = await self.publicGetCandles(self.extend(request, params))
        return self.parse_ohlcvs(candles, market, timeframe, since, limit)

    async def fetch_balance(self, params={}):
        await self.load_markets()
        balances = await self.privateGetBalances(params)
        result = {'info': balances}
        for i in range(0, len(balances)):
            balance = balances[i]
            code = self.safe_currency_code(balance['asset'])
            account = self.account()
            account['free'] = self.safe_float(balance, 'free')
            account['used'] = self.safe_float(balance, 'locked')
            result[code] = account
        return self.parse_balance(result)

    def parse_order(self, order, market=None):
        # {
        #     "id": 5000001,
        #     "uid": "sdnrauah626opk7zu7w7c",
        #     "pairSymbol": "ETH_MAS",
        #     "price": 0.00001679,
        #     "amount": 595.5926,
        #     "remain": 0,
        #     "orderType": "LIMIT",
        #     "actionType": 1,
        #     "status": 1,
        #     "createdAt": 1584687831
        # }
        market = self.marketsById[order['market']]
        symbol = market['symbol']
        side = None
        if order['actionType'] == 1:
            side = 'buy'
        elif order['actionType'] == 0:
            side = 'sell'
        status = None
        if order['status'] == 10 or order['status'] == 0:
            status = 'open'
        elif order['status'] == 1:
            status = 'closed'
        elif order['status'] == 2:
            status = 'canceled'
        timestamp = self.safe_integer(order, 'createdAt') * 1000
        type = self.safe_string_lower(order, 'orderType')
        price = self.safe_float(order, 'price')
        amount = self.safe_float(order, 'amount')
        remaining = self.safe_float(order, 'remain')
        filled = amount - remaining
        cost = price * filled
        return {
            'id': self.safe_string(order, 'uid'),
            'clientOrderId': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': price,
            'cost': cost,
            'average': None,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'info': order,
            'trades': None,
        }

    async def _fetch_orders(self, symbol=None, since=None, limit=None, params={}, status=None):
        await self.load_markets()
        request = {}
        market = None
        if symbol:
            market = self.market(symbol)
            request['market'] = market['id']
        if since:
            request['start'] = int(math.floor(since / 1000))
        if limit:
            request['limit'] = limit
        if status:
            request['status'] = status
        orders = await self.privateGetGetMyOrders(self.extend(request, params))
        return self.parse_orders(orders, market, since, limit)

    async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        return self._fetch_orders(symbol, since, limit, params)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        return self._fetch_orders(symbol, since, limit, params, 'OPENED')

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        return self._fetch_orders(symbol, since, limit, params, 'FINISHED')

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
            'amount': self.amount_to_precision(symbol, amount),
            'price': self.price_to_precision(symbol, price),
        }
        if type is not None:
            request['order_type'] = type.upper()
        if side == 'buy':
            request['type'] = 'BUY'
        elif side == 'sell':
            request['type'] = 'SELL'
        data = await self.privatePostPlaceOrder(self.extend(request, params))
        return self.parse_order(data)

    async def cancel_order(self, id, symbol=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
            'uid': id,
        }
        return await self.privatePostCancelOrder(self.extend(request, params))

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {}
        if symbol:
            market = self.market(symbol)
            request['market'] = market['id']
        if since:
            request['startTime'] = int(math.floor(since / 1000))
        if limit:
            request['limit'] = limit
        trades = await self.privateGetGetMyTrading(self.extend(request, params))
        return self.parse_trades(trades)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.implode_params(self.urls['api'], {
            'hostname': self.hostname,
        }) + '/' + path
        if api == 'public':
            if params:
                url += '?' + self.urlencode(params)
        else:
            self.check_required_credentials()
            headers = {}
            headers['api-key'] = self.apiKey
            if not ('time_stamp' in params):
                params['time_stamp'] = self.seconds()
            # Create signature
            keys = list(params.keys())
            keys.sort()
            keysLength = len(keys)
            plainText = ''
            for i in range(0, keysLength - 1):
                plainText += self.safe_string(params, keys[i]) + '_'
            plainText += self.safe_string(params, keys[keysLength - 1])
            headers['signature'] = self.hmac(self.encode(plainText), self.encode(self.secret), hashlib.sha256)
            if method == 'GET':
                url += '?' + self.urlencode(params)
            elif params:
                body = self.urlencode(params)
                headers['Content-Type'] = 'application/x-www-form-urlencoded'
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    async def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
        response = await self.fetch2(path, api, method, params, headers, body)
        if response:
            if 'data' in response:
                return response['data']
            else:
                errorMsg = response['message']
                raise ExchangeError(errorMsg)
        return response
