import logging
import json
from datetime import datetime
from rest_framework import response, schemas, viewsets, mixins
from rest_framework.decorators import *
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication, BasicAuthentication

from autotrader.models import *
from autotrader.serializers import *


LOG=logging.getLogger(__name__)


class CurrencyViewSet(viewsets.ModelViewSet):

    queryset = Currency.objects
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = CurrencySerializer
    

class MarketViewSet(viewsets.ModelViewSet):

    queryset = Market.objects.none()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = MarketSerializer
    
    def get_queryset(self):
        return Market.objects.filter(left__account__user=self.request.user)


class OrderViewSet(viewsets.ModelViewSet):

    queryset = Order.objects.none()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = OrderSerializer
    
    def get_queryset(self):
        return Order.objects.filter(market__left__account__user=self.request.user).order_by('-state','-created')
    

class TickerViewSet(viewsets.ModelViewSet):

    queryset = Ticker.objects
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = TickerSerializer
    

class TradeViewSet(viewsets.ModelViewSet):

    queryset = Trade.objects.none()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = TradeSerializer
    
    def get_queryset(self):
        return Trade.objects.filter(strategy__owner=self.request.user).exclude(state__in=[Trade.S_CLOSED, Trade.S_CANCELLED]).order_by('-state','id')
    

class WalletViewSet(viewsets.ModelViewSet):

    queryset = Wallet.objects.none()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = WalletSerializer
    
    def get_queryset(self):
        return Wallet.objects.filter(account__user=self.request.user)

    
class StrategyViewSet(viewsets.ModelViewSet):

    queryset = Strategy.objects.none()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    serializer_class = StrategySerializer
    
    def get_queryset(self):
        return Strategy.objects.filter(owner=self.request.user).order_by('order','market')

