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.decorators import detail_route
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, FullUserProjectSerializer, FullBeaconManagerSerializer


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 FullBeaconManagerViewSet(viewsets.ModelViewSet):
    """
    API for places
    """
    queryset = BeaconManager.objects.all()
    serializer_class = FullBeaconManagerSerializer


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

    @detail_route()
    def beacons(self, request, pk=None):
        user_project = UserProject.objects.get(pk=pk)
        beacons = []
        beacon_managers = user_project.beacon_managers.all()
        for beacon_manager in beacon_managers:
            serializer_beacon = BeaconSerializer(beacon_manager.beacon, context={'request': request})
            serializer_data = serializer_beacon.data
            serializer_beacon_manager = BeaconManagerSerializer(beacon_manager, context={'request': request})
            serializer_data.update({'beacon_manager' : serializer_beacon_manager.data['url']})
            beacons.append(serializer_data)

        return Response(data=beacons)

    @detail_route()
    def all(self, request, pk=None):
        user_project = UserProject.objects.get(pk=pk)
        user_project_serializer = FullUserProjectSerializer(user_project, context={'request': request})
        return Response(data=user_project_serializer.data)

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:

        sites = []
        sites_objects = beacon_manager.sites.all()
        for site in sites_objects:
            serializer_sites = SiteSerializer(site, context={'request': request})
            sites_data = serializer_sites.data

            category_serializer = CategorySerializer(site.category, many=True, context={'request': request})
            sites_data['category'] =category_serializer.data[0]['name']
            sites.append(sites_data)

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

        serializer_data['beacon'] = serializer_beacon.data
        return Response(serializer_data)

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

    @detail_route()
    def all(self, request, pk=None):
        category = Category.objects.all()
        category_serializer = CategorySerializer(category,many=True,  context={'request': request})
        category_data = category_serializer.data
        data = []
        for category in category_data:
            data.append(category['name'])
        return Response(data=data)

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)
    user_projects = UserProject.objects.filter(author=request.user)
    data = {}
    data['user_projects'] = user_projects
    data['user_id'] = request.user.id
    return render_to_response('user_panel/content/dashboard.html', data, context)

def beacons(request):
    context = RequestContext(request)
    data = {}
    data['user_id'] = request.user.id
    return render_to_response('user_panel/content/beacon_list.html', data, context)

def project(request, project_id):
    context = RequestContext(request)
    data = {}
    user_project = UserProject.objects.get(id=project_id)
    data['user_project'] = user_project
    data['project_id'] = project_id
    return render_to_response('user_panel/content/project.html', data, context)
