from rest_framework.response import Response
from rest_framework.views import APIView
from inbound.models import *
import uuid


class AddVisitorToCRM(APIView):
    @staticmethod
    def post(request, format=None):
        try:
            email = request.DATA["email"]
            first_name = request.DATA["first_name"]
            last_name = request.DATA["last_name"]
            organization = request.DATA["organization"]
            cookie = request.DATA["cookie"]
            lead, newlead = Leads.objects.update_or_create(email=email,
                                                           defaults={'first_name': first_name, 'last_name': last_name,
                                                                     'organization': organization})
            c, newcookie = Cookies.objects.get_or_create(cookie=cookie)
            a, newalignment = Alignment.objects.get_or_create(cookie=c, lead=lead)
        except Exception as e:
            return Response(str(e), status=400)
        else:
            return Response(status=201)


class LogSession(APIView):
    @staticmethod
    def post(request, format=None):
        try:
            cookie = request.DATA["cookie"]
            c, newcookie = Cookies.objects.get_or_create(cookie=cookie)
            s = Sessions(cookie=c)
            s.save()
        except Exception as e:
            return Response(str(e), status=400)
        else:
            return Response(status=201)


class LogAlignment(APIView):
    @staticmethod
    def post(request, format=None):
        try:
            email = request.DATA["email"]
            cookie = request.DATA["cookie"]
            lead, newlead = Leads.objects.update_or_create(email=email)
            c, newcookie = Cookies.objects.get_or_create(cookie=cookie)
            a, newalignment = Alignment.objects.get_or_create(cookie=c, lead=lead)
        except Exception as e:
            return Response(str(e), status=400)
        else:
            return Response(status=201)


class Cookie(APIView):
    @staticmethod
    def post(request, format=None):
        try:
            cookie = uuid.uuid4().hex
            c, newcookie = Cookies.objects.get_or_create(cookie=cookie)
        except Exception as e:
            return Response(str(e), status=400)
        else:
            return Response(c, status=201)



