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


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

    @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


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
    return render_to_response('user_panel/content/dashboard.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
    #user_project_serializer = UserProjectSerializer(user_project, context={'request': request})
    #data['project_data'] = user_project_serializer.data
    data['project_id'] = project_id
    #data['beacon_display']  = []
    # beacon_managers =  user_project.beacon_managers.all()
    # for beacon_manager in beacon_managers:
    #     beacon_serializer = BeaconSerializer(beacon_manager.beacon,context={'request': request})
    #     beacon_data = beacon_serializer.data
    #     my_sites = beacon_manager.sites.filter(author=request.user.pk)
    #     site_serializer = SiteSerializer(my_sites, many=True, context={'request': request})
    #     sites_data = site_serializer.data
    #     data['beacon_display'].append({'beacon':beacon_data,'sites' :sites_data})
    return render_to_response('user_panel/content/project.html', data, context)
