from datetime import datetime

from chipmunkdb.ChipmunkDb import ChipmunkDb

import coinlib.dataWorker_pb2 as statsModel
import coinlib.dataWorker_pb2_grpc as stats
import simplejson as json
from coinlib.helper import is_in_ipynb
import ipynb_path
from grpc._cython.cygrpc import CompressionAlgorithm
from grpc._cython.cygrpc import CompressionLevel
from coinlib.Registrar import Registrar
import grpc

import inspect
from google.protobuf.json_format import MessageToDict
import os
import sys


class CoinlibDataInterface:
    channel = None

    def __init__(self):
        self.registrar = Registrar()


    def connect(self):
        self.channel = self.createChannel()
        self.dataInterface = stats.DataLoaderWorkerStub(self.channel)
        pass

    def createChannel(self):
        chan_ops = [('grpc.max_receive_message_length', 1000 * 1024 * 1024),
                    ('grpc.default_compression_algorithm', CompressionAlgorithm.gzip),
                    ('grpc.grpc.default_compression_level', CompressionLevel.high)]
        return grpc.insecure_channel(self.registrar.get_coinlib_backend_grpc(), options=chan_ops,
                                     compression=grpc.Compression.Gzip)

    def getAllExchanges(self):

        b = statsModel.ExchangeDataRequestInfo()

        ret = self.dataInterface.getAllExchanges(b)

        return ret.exchanges

    def getAllSymbols(self, additionalDataFeatures=[]):

        b = statsModel.SymbolDataRequestInfo()
        b.additionalDataFeatures = json.dumps(additionalDataFeatures)

        ret = self.dataInterface.getAllSymbols(b)

        return ret.symbols

    def getAvailableFeatures(self):

        b = statsModel.AdditionalDataFeatureRequest()

        ret = self.dataInterface.getAdditionalDataFeatures(b)

        return ret.featureInfos

    def getMarketData(self, symbol, startDate, endDate, timeframe="1h", exchange=None, contractType="spot", additionalDataFeatures=[]):

        b = statsModel.MarketDataRequest()
        s = statsModel.SymbolBrokerSymbolSmall()
        if exchange is not None:
            s.exchange_id = exchange
        s.symbol = symbol

        b.symbol.CopyFrom(s)
        b.timeframe = timeframe
        b.startDate = datetime.strftime(startDate, "%Y-%m-%dT%H:%M:%S.%fZ")
        b.endDate = datetime.strftime(endDate, "%Y-%m-%dT%H:%M:%S.%fZ")
        b.contractType = contractType
        b.additionalDataFeatures = json.dumps(additionalDataFeatures)

        ret = self.dataInterface.getMarketData(b)

        self.chipmunkDb = ChipmunkDb(self.registrar.chipmunkdb)
        df = self.chipmunkDb.collection_as_pandas_additional(ret.database_id, additionalCollections=[])

        return df
