import random
import json

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.views.generic.base import View, TemplateView
from django.http import HttpResponse
from django.db.models import Q
from django.contrib.sites.models import Site
from django.conf import settings

from booking.models import DEFAULT_PEOPLE__LIST, DEFAULT_CHILDREN_LIST, DEFAULT_ROOM_LIST
from .models import Property, PropertyWeb, PropertyWebPhoto, ExtraService, PropertyWebContact
from .models import PLACE_TYPES
from availability.models import Availability
from core.views import Search
from core.utils import generate_condition_message, generate_deposit_message, generate_children_message
from banner.views import ListaBanners

from django.utils import timezone
from django.utils.dateparse import parse_date
import datetime
from datetime import timedelta, date


#from django.views.decorators.cache import never_cache


#@never_cache
class PropertyView(Search, TemplateView):
    template_name = 'property/property.html'
    sdebug=False
    def is_search(self, kwargs):
        if 'nights' in kwargs and 'day' in kwargs:
            return True
        else:
            # data can go in kwargs or in request.GET
            g = self.request.GET
            return 'nights' in g and 'day' in g

    def get_data(self):
        d = self.kwargs
        g = self.request.GET
        if 'nights' not in d:
            d = g
        #New search JALS
        data = g
        destinoid = data.get('destinoid', '')
        nrooms = data.get('rooms', '1')        
        day = data.get('day', '1')        
        month = data.get('month','1')
        year = data.get('year','2000')
        nights = data.get('nights','0')
        try:
            checkin =  parse_date(year+'-'+month+'-'+day)
            checkout =  checkin + timedelta(int(nights))
            start = checkin
            end = checkout
        except:
            checkin=None
            checkout=None
        
        ## JALS data es un QureyDict
        #diccionario = data.dict()
        habitaciones = []
        contadoradultos = 0
        contadorchild =0
        for x in range(int(nrooms)):
            adultos = data.get('adultsRoom'+str(x+1), '0')
            contadoradultos = contadoradultos + int(adultos)
            children =  data.get('childrenRoom'+str(x+1), '0')
            contadorchild = contadorchild + int(children)
            childrenAges = []
            try:
                for y in range(int(children)):
                    age = data.get('child' + str(y+1) + 'Room'+str(x+1),'0')
                    if age != '0':
                        childrenAges.append(int(age))
                
            except:
                children=0
            habitacion = {'adultos':int(adultos), 'children': int(children), 'childrenages': childrenAges }
            habitaciones.append(habitacion)
        peticion = {'checkin': checkin.strftime("%Y-%m-%d"), 'checkout':checkout.strftime("%Y-%m-%d"),'nights': nights, 'hotel': destinoid, 'habitaciones': habitaciones}

        #End new Seach params
        query = {
            'start': checkin.strftime("%Y-%m-%d"),
            'end': checkout.strftime("%Y-%m-%d"),
            'peticion': peticion,
            'nights': nights,
            'nrooms': str(len(habitaciones)),
            'paramstr': data.urlencode(),
            'people': contadoradultos,
            'children': contadorchild
        }
        if self.sdebug:
            print('--------------------->>>>>>>>>>>Entrada en el get_data de Property: ', peticion)
        return query

    def query_avail(self, ctx, start, end=None, mode='range'):
        prop = ctx['prop'].id
        avail = []
        excluidos=[]
        if mode == 'range':
            avail = Availability.objects.filter(date__range=[start, end],
                                                property_id=prop,
                                                rooms_to_shell__gt=0,
                                                availability__in=['0', '3'])
        elif mode == 'normal':
            avail = Availability.objects.filter(date=start,
                                                property_id=prop,
                                                rooms_to_shell__gt=0,
                                                availability__in=['0', '3'])
        elif mode == 'gte':
            avail = Availability.objects.filter(date__gte=start,
                                                property_id=prop,
                                                rooms_to_shell__gt=0,
                                                availability__in=['0', '3'])
        for av in avail:
           if av.release > 0:
              fecha = today = datetime.date.today()
              nuevafecha = fecha  + timedelta(av.release)
              if nuevafecha <= av.date :
                if self.sdebug:
                   print('AV insertado por release: ' + str(av.release) + ' fecha del av: ' + str(av.date) + ' Fecha que se compara: ' + str(nuevafecha))
              else:
                excluidos.append(av.id)
                if self.sdebug:
                   print('AV descartado por release: '+ str(av.release) + ' fecha del av: ' + str(av.date) + ' Fecha que se compara: ' + str(nuevafecha))
        if len(excluidos)>0:
           avail = avail.exclude(pk__in=excluidos)
        return avail

    def get_context_data(self, *args, **kwargs):
        ctx = super(Search, self).get_context_data(*args, **kwargs)
        ctx['prop'] = get_object_or_404(Property, slug=kwargs['slug'])
        if ctx['prop'].active == False:
            return redirect('/')
        
        ctx['imgs'] = PropertyWebPhoto.objects.filter(Q(web__prop=ctx['prop']))
        ctx['extras'] = ExtraService.objects.filter(Q(prop=ctx['prop']))
        ctx['contact'] = PropertyWebContact.objects.filter(Q(web__prop=ctx['prop']))[:1]
        ctx['condition_message'] = generate_condition_message(property=ctx['prop'])
        ctx['deposit_message'] = generate_deposit_message(property=ctx['prop'])
        ctx['children_message'] = generate_children_message(property=ctx['prop'])
        ctx['gmaps_apikey'] = settings.GMAPS_APIKEY
        ctx['is_search'] = self.is_search(kwargs)
        ctx['query'] = self.get_data()
        #New Search establecer el contexto:
        ctx['checkin'] = ctx['query']['peticion']['checkin']
        ctx['checkout'] = ctx['query']['peticion']['checkout']
        ctx['peticion'] = ctx['query']['peticion']
        ctx['paramstr'] = ctx['query']['paramstr']
        ctx['nights'] = ctx['query']['peticion']['nights']
        ctx['nrooms'] = str(len(ctx['query']['peticion']['habitaciones']))
        ctx['people'] = ctx['query']['people']
        ctx['children'] = ctx['query']['children']
        #tipo establecimiento: no para busqueda dentro del property
        #end new search
        if self.sdebug:
            print('Query dentro de property: ', ctx['paramstr'])
        if ctx['is_search']:
            ctx.update(self.search_availability(ctx))
            # rooms = ctx['results']['rooms']
            # rooms = sorted(rooms, key=lambda x: x.min_price(),reverse=False)
            # roomsnocero = filter(lambda t: t.min_price() > 0, rooms)
            # roomscero = filter(lambda t: t.min_price() <= 0, rooms)
            # rooms = roomsnocero + roomscero
            # ctx['results'][0]['rooms'] = rooms
        else:
            rooms = ctx['prop'].rooms.all()
            #ordenar los rooms por min_price que es una funcion! las mas baratas primero!
            rooms = sorted(rooms, key=lambda x: x.min_price(),reverse=False)
            roomsnocero = filter(lambda t: t.min_price() > 0, rooms)
            roomscero = filter(lambda t: t.min_price() <= 0, rooms)
            rooms = roomsnocero + roomscero
            ctx['rooms'] = rooms

        ctx['people_list'] = DEFAULT_PEOPLE__LIST
        ctx['children_list'] = DEFAULT_CHILDREN_LIST
        ctx['rooms_list'] = DEFAULT_ROOM_LIST
        ctx['prop'] = ctx['prop']
        

        return ctx


class AllProperties(TemplateView):
    template_name = 'property/all.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(AllProperties, self).get_context_data(*args, **kwargs)

        props = Property.objects.filter(active=True)
        # banners = list(ListaBanners())
        # random.shuffle(banners)
        # random order
        props = list(Property.objects.filter(active=True))
        random.shuffle(props)
        from banner.reports import *
        banners = JsonData.get_banner()

        ctx['people_list'] = DEFAULT_PEOPLE__LIST
        ctx['children_list'] = DEFAULT_CHILDREN_LIST
        ctx['people_list'] = DEFAULT_PEOPLE__LIST
        ctx['rooms_list'] = DEFAULT_ROOM_LIST
        ctx['place_types'] = PLACE_TYPES
        ctx['props'] = props
        ctx['gmaps_apikey'] = settings.GMAPS_APIKEY
        ctx['banners']=banners
        return ctx

class NewEmbedSearchPropertyView(TemplateView):
    template_name = 'property/new_embed_search_property.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(NewEmbedSearchPropertyView, self).get_context_data(*args, **kwargs)
        ctx['prop'] = get_object_or_404(Property, slug=kwargs['slug'])
        try:
            current_site = Site.objects.get_current()
            domain = current_site.domain
        except:
            domain = "https://conilhospeda.com"
        ctx['domain'] = domain
        return ctx


class EmbedSearchPropertyView(TemplateView):
    template_name = 'property/embed_search_property.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(EmbedSearchPropertyView, self).get_context_data(*args, **kwargs)
        ctx['prop'] = get_object_or_404(Property, slug=kwargs['slug'])
        try:
            current_site = Site.objects.get_current()
            domain = current_site.domain
        except:
            domain = "https://conilhospeda.com"
        ctx['domain'] = domain
        return ctx



class ApiGetAllLatLng(View):
    def get(self, request, *args, **kwargs):
        alls = []
        for p in Property.objects.filter(active=True):
            alls.append({"name": p.name, "slug": p.slug, "lat": p.geo_lat, "lng": p.geo_lng, "type": p.type,"type2":p.type2})
        json_data = alls
        return HttpResponse(json.dumps(json_data), content_type="application/json")
api_get_all_latlng = ApiGetAllLatLng.as_view()


class ApiGetLatLng(View):
    def get(self, request, *args, **kwargs):
        p = Property.objects.get(Q(slug=kwargs['slug']))
        if p:
            json_data = [{"name": p.name, "slug": p.slug, "lat": p.geo_lat, "lng": p.geo_lng, "type": p.type,"type2":p.type2}]
        else:
            json_data = {}
        return HttpResponse(json.dumps(json_data), content_type="application/json")
api_get_latlng = ApiGetLatLng.as_view()
