import json
import logging

# Create your views here.
from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny

from django.contrib.gis.geoip2 import GeoIP2
from django.contrib.gis.geos import Point

from ipware import get_client_ip

from back_latienda.permissions import IsStaff

from products.models import Product
from companies.models import Company

from stats.models import StatsLog
from stats.serializers import StatsLogSerializer


class StatsLogViewSet(viewsets.ModelViewSet):
    queryset = StatsLog.objects.all()
    serializer_class = StatsLogSerializer
    permission_classes = [IsStaff,]


@api_view(['POST'])
@permission_classes([AllowAny,])
def track_user(request):
    """Track user actions on the site

    Three types of actions to track:
    - Load product details: view=True
    - Load shop URL: shop=True
    - Load company profile: view=True, action_object['model'] = 'company'

    Params:
    {
        'action': 'view' | 'shop',
        'action_object': {
            'model': 'product' | 'company',
            id: 1,
        },
        'ip': '2134.234.234.2134',
        'geo': (324.32, 32423.23)
    }
    """
    try:
        data = request.data

        if data.get('geo'):
            coordinates = (data['geo'].get('longitude'), data['geo'].get('latitude'))
        else:
            coordinates = None

        # gather instance data
        instance_data = {
            'action_object': data.get('action_object'),
            'user': None if request.user.is_anonymous else request.user,
            'anonymous': request.user.is_anonymous,
            'ip_address': data.get('ip'),
            'geo': Point(coordinates),
        }

        if data['action_object'].get('model') == 'product':
            instance_data['action_object'] = Product.objects.get(id=data['action_object'].get('id'))
        elif data['action_object'].get('model') == 'company':
            instance_data['action_object'] = Company.objects.get(id=data['action_object'].get('id'))

        if data.get('action') == 'view':
            instance_data['view'] = True
        elif data.get('action') == 'shop':
            instance_data['shop'] = True

        # crate new instance
        new_stat = StatsLog.objects.create(**instance_data)
        return Response(status=status.HTTP_201_CREATED)
    except Exception as e:
        logging.error(f"Stats could not be created: {str(e)}")
        return Response(f"Process could not be registered [{str(type(e))}]: {str(e)}", status=status.HTTP_406_NOT_ACCEPTABLE)
