# -*- 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.base.exchange import Exchange
import hashlib
import json
from ccxt.base.errors import ExchangeError


class crypton (Exchange):

    def describe(self):
        return self.deep_extend(super(crypton, self).describe(), {
            'id': 'crypton',
            'name': 'Crypton',
            'countries': ['EU'],
            'rateLimit': 500,
            'version': '1',
            'has': {
                'fetchDepositAddress': True,
                'fetchMyTrades': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchTicker': False,
                'fetchTickers': True,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/41334251-905b5a78-6eed-11e8-91b9-f3aa435078a1.jpg',
                'api': 'https://api.cryptonbtc.com',
                'www': 'https://cryptonbtc.com',
                'doc': 'https://cryptonbtc.docs.apiary.io/',
                'fees': 'https://help.cryptonbtc.com/hc/en-us/articles/360004089872-Fees',
            },
            'api': {
                'public': {
                    'get': [
                        'currencies',
                        'markets',
                        'markets/{id}',
                        'markets/{id}/orderbook',
                        'markets/{id}/trades',
                        'tickers',
                    ],
                },
                'private': {
                    'get': [
                        'balances',
                        'orders',
                        'orders/{id}',
                        'fills',
                        'deposit_address/{currency}',
                        'deposits',
                    ],
                    'post': [
                        'orders',
                    ],
                    'delete': [
                        'orders/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': 0.0020,
                    'taker': 0.0020,
                },
            },
        })

    def fetch_markets(self):
        response = self.publicGetMarkets()
        markets = response['result']
        result = []
        keys = list(markets.keys())
        for i in range(0, len(keys)):
            id = keys[i]
            market = markets[id]
            baseId = market['base']
            quoteId = market['quote']
            base = self.common_currency_code(baseId)
            quote = self.common_currency_code(quoteId)
            symbol = base + '/' + quote
            precision = {
                'amount': 8,
                'price': self.precision_from_string(self.safe_string(market, 'priceStep')),
            }
            active = market['enabled']
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': active,
                'info': market,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': self.safe_float(market, 'minSize'),
                        'max': None,
                    },
                    'price': {
                        'min': self.safe_float(market, 'priceStep'),
                        'max': None,
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
            })
        return result

    def fetch_balance(self, params={}):
        self.load_markets()
        balances = self.privateGetBalances(params)
        result = {'info': balances}
        keys = list(balances.keys())
        for i in range(0, len(keys)):
            id = keys[i]
            currency = self.common_currency_code(id)
            account = self.account()
            balance = balances[id]
            total = float(balance['total'])
            free = float(balance['free'])
            used = float(balance['locked'])
            account['total'] = total
            account['free'] = free
            account['used'] = used
            result[currency] = account
        return self.parse_balance(result)

    def fetch_order_book(self, symbol, limit=None, params={}):
        self.load_markets()
        orderbook = self.publicGetMarketsIdOrderbook(self.extend({
            'id': self.market_id(symbol),
        }, params))
        return self.parse_order_book(orderbook)

    def parse_ticker(self, ticker, market=None):
        symbol = None
        if market:
            symbol = market['symbol']
        last = self.safe_float(ticker, 'last')
        relativeChange = self.safe_float(ticker, 'change24h', 0.0)
        return {
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': self.safe_float(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_float(ticker, 'ask'),
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': relativeChange * 100,
            'average': None,
            'baseVolume': self.safe_float(ticker, 'volume24h'),
            'quoteVolume': None,
            'info': ticker,
        }

    def fetch_tickers(self, symbols=None, params={}):
        self.load_markets()
        tickers = self.publicGetTickers(params)
        keys = list(tickers.keys())
        result = {}
        for i in range(0, len(keys)):
            id = keys[i]
            ticker = tickers[id]
            market = None
            symbol = id
            if id in self.markets_by_id:
                market = self.markets_by_id[id]
                symbol = market['symbol']
            else:
                symbol = self.parse_symbol(id)
            result[symbol] = self.parse_ticker(ticker, market)
        return result

    def parse_trade(self, trade, market=None):
        timestamp = self.parse8601(trade['time'])
        symbol = None
        if 'market' in trade:
            marketId = trade['market']
            if marketId in self.markets_by_id:
                market = self.markets_by_id[marketId]
            else:
                symbol = self.parse_symbol(marketId)
        if market is not None:
            symbol = market['symbol']
        fee = None
        if 'fee' in trade:
            fee = {
                'cost': self.safe_float(trade, 'fee'),
                'currency': self.common_currency_code(trade['feeCurrency']),
            }
        return {
            'id': str(trade['id']),
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': trade['side'],
            'price': self.safe_float(trade, 'price'),
            'amount': self.safe_float(trade, 'size'),
            'order': self.safe_string(trade, 'orderId'),
            'fee': fee,
        }

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        request = {
            'id': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetMarketsIdTrades(self.extend(request, params))
        return self.parse_trades(response['result'], market, since, limit)

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        request = {}
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetFills(self.extend(request, params))
        trades = self.parse_trades(response['result'], market, since, limit)
        return self.filter_by_symbol(trades, symbol)

    def parse_order(self, order, market=None):
        id = str(order['id'])
        status = order['status']
        side = order['side']
        type = order['type']
        symbol = None
        marketId = order['market']
        if marketId in self.markets_by_id:
            market = self.markets_by_id[marketId]
            symbol = market['symbol']
        else:
            symbol = self.parse_symbol(marketId)
        timestamp = self.parse8601(order['createdAt'])
        iso8601 = self.iso8601(timestamp)
        fee = None
        if 'fee' in order:
            fee = {
                'cost': float(order['fee']),
                'currency': self.common_currency_code(order['feeCurrency']),
            }
        price = self.safe_float(order, 'price')
        amount = self.safe_float(order, 'size')
        filled = self.safe_float(order, 'filledSize')
        remaining = amount - filled
        cost = filled * price
        result = {
            'info': order,
            'id': id,
            'timestamp': timestamp,
            'datetime': iso8601,
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': price,
            'cost': cost,
            'average': None,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': fee,
        }
        return result

    def fetch_order(self, id, symbol=None, params={}):
        self.load_markets()
        request = {
            'id': id,
        }
        response = self.privateGetOrdersId(self.extend(request, params))
        return self.parse_order(response['result'])

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            request['market'] = self.market_id(symbol)
        response = self.privateGetOrders(self.extend(request, params))
        return self.parse_orders(response['result'], market, since, limit)

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        self.load_markets()
        order = {
            'market': self.market_id(symbol),
            'side': side,
            'type': type,
            'size': self.amount_to_precision(symbol, amount),
            'price': self.price_to_precision(symbol, price),
        }
        response = self.privatePostOrders(self.extend(order, params))
        return self.parse_order(response['result'])

    def cancel_order(self, id, symbol=None, params={}):
        self.load_markets()
        request = {
            'id': id,
        }
        response = self.privateDeleteOrdersId(self.extend(request, params))
        return self.parse_order(response['result'])

    def parse_symbol(self, id):
        base, quote = id.split('-')
        base = self.common_currency_code(base)
        quote = self.common_currency_code(quote)
        return base + '/' + quote

    def fetch_deposit_address(self, code, params={}):
        self.load_markets()
        currency = self.currency(code)
        response = self.privateGetDepositAddressCurrency(self.extend({
            'currency': currency['id'],
        }, params))
        result = response['result']
        address = self.safe_string(result, 'address')
        tag = self.safe_string(result, 'tag')
        self.check_address(address)
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        request = '/' + self.implode_params(path, params)
        query = self.omit(params, self.extract_params(path))
        if method == 'GET':
            if query:
                request += '?' + self.urlencode(query)
        url = self.urls['api'] + request
        if api == 'private':
            self.check_required_credentials()
            timestamp = str(self.milliseconds())
            payload = ''
            if method != 'GET':
                if query:
                    body = self.json(query)
                    payload = body
            what = timestamp + method + request + payload
            signature = self.hmac(self.encode(what), self.encode(self.secret), hashlib.sha256)
            headers = {
                'CRYPTON-APIKEY': self.apiKey,
                'CRYPTON-SIGNATURE': signature,
                'CRYPTON-TIMESTAMP': timestamp,
                'Content-Type': 'application/json',
            }
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body):
        if body[0] == '{':
            response = json.loads(body)
            success = self.safe_value(response, 'success')
            if not success:
                raise ExchangeError(self.id + ' ' + body)
