from django.contrib import auth
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, render_to_response, redirect
from django.template import RequestContext

# Create your views here.
from rest_framework import viewsets
import rest_framework
from rest_framework.response import Response
from rest_framework.views import APIView
from Hub.models import Beacon, BeaconManager, Site, Category, UserProject
from Hub.serializers import BeaconSerializer, BeaconManagerSerializer, SiteSerializer, CategorySerializer, \
    UserSerializer, UserProjectSerializer


class BeaconViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = Beacon.objects.all()
    serializer_class = BeaconSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

class BeaconManagerViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = BeaconManager.objects.all()
    serializer_class = BeaconManagerSerializer

class UserProjectViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = UserProject.objects.all()
    serializer_class = UserProjectSerializer


class SiteViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = Site.objects.all()
    serializer_class = SiteSerializer



class UuidBeaconViewSet(APIView):
    """
    API for places
    """
    queryset = Beacon.objects.all()
    serializer_class = BeaconSerializer

    def get(self, request, pk, category_name = None,format=None):
        try:
            beacon = Beacon.objects.get(uuid = pk)
        except ObjectDoesNotExist:
            return Response(status=rest_framework.status.HTTP_400_BAD_REQUEST, data={"This beacon is not exist"})
        beacon_manager = BeaconManager.objects.get(beacon=beacon)
        if category_name:
            try:
                category = Category.objects.get(name=category_name)
            except ObjectDoesNotExist:
                return Response(status=rest_framework.status.HTTP_400_BAD_REQUEST, data={"This category is not exist"})
            try:
                site = beacon_manager.sites.get(category=category)
            except ObjectDoesNotExist:
                return Response(status=rest_framework.status.HTTP_400_BAD_REQUEST, data={"Any link do not have this category"})
            serializer_sites = SiteSerializer(site, context={'request': request})
        else:
            serializer_sites = SiteSerializer(beacon_manager.sites, many=True, context={'request': request})

        serializer = BeaconManagerSerializer(beacon_manager, context={'request': request})
        serializer_data = serializer.data
        serializer_beacon = BeaconSerializer(beacon_manager.beacon, context={'request': request})
        serializer_data['sites'] = serializer_sites.data
        serializer_data['beacon'] = serializer_beacon.data
        return Response(serializer_data)

class CategoryViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer


def login_page(request):
    context = RequestContext(request)

    if not request.method == 'POST':
        return render_to_response('page/content/login.html', {}, context)

    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    user = auth.authenticate(username=username, password=password)
    if user:
        login(request, user)
        return HttpResponseRedirect('/', {}, context)
    else:
        return HttpResponse("Invalid login details supplied.")

def main_page(request):
    context = RequestContext(request)
    if request.user.is_authenticated():
        return redirect('/dashboard')
    else:
        return render_to_response('page/content/main_page.html', {}, context)

def dashboard(request):
    context = RequestContext(request)
    return render_to_response('user_panel/content/dashboard.html', {}, context)

def project(request, project_id):
    context = RequestContext(request)
    data = {}
    user_project = UserProject.objects.get(id=project_id)
    user_project_serializer = UserProjectSerializer(user_project, context={'request': request})
    beacons_serializer = BeaconSerializer(user_project.beacons, many=True,context={'request': request})

    data['project_data'] = user_project_serializer.data
    data['project_data']['beacons'] = beacons_serializer.data

    return render_to_response('user_panel/content/project.html', data, context)
