# -*- encoding: utf-8 -*-
from django.shortcuts import render
from django.contrib.auth import login, authenticate, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
import json
from forms import *
from models import *
from allauth.socialaccount.models import SocialToken

def user_logout(request):
	logout(request)
	return HttpResponseRedirect(reverse('landing'))

def landing(request):
	return render(request, 'app/landing.html',locals())

def login(request, empresa, token):
	if not request.user.is_anonymous():
		return HttpResponseRedirect(reverse('index'))
	form = LoginForm()
	if request.method == "POST":
		form = LoginForm(request.POST)
		if form.is_valid():
			user = form.cleaned_data["user"]
			password = form.cleaned_data["password"]
			company = form.cleaned_data["company"]
			username = company + '_' + user
			if not company:
				username = 'ZaresApp_Castellanos'
			access = authenticate(username=username, password=password)
			if access is not None:			
				if access.is_active:
					login(request, access)
					return HttpResponseRedirect(reverse('index'))
				else:
					mensaje="Usuario esta desactivado"		
			else:
				mensaje="Usuario o contraseña incorrecto"
		else:
			print form.errors
			mensaje="Usuario o contraseña incorrecto"
	return render(request, 'app/login.html',locals())

def index(request):
	return render(request, 'app/sell_point.html',locals())

@csrf_exempt
def menus(request):
	form = MenusForm()
	if request.method == "POST":
		if 'jstree' in request.POST:
			menu = Menu.objects.filter(id = request.POST.get('menu_id'))[0]
			#menu.nivel =  int(request.POST.get('level')) + 1
			if request.POST.get('depend_id'):
				menu.parent = Menu.objects.filter(id = request.POST.get('depend_id'))[0]
			else:
				menu.parent = None
			menu.save()
			return HttpResponse(json.dumps({"data": "true"}),content_type="application/json")
		if 'add_menu' in request.POST:
			form = MenusForm(request.POST)
			if form.is_valid():
				obj = form.save(commit = False)
				obj.company = request.user.company
				obj.save()
				messages.success(request, 'Guardado con éxito!')
				form = MenusForm()
			else:
				messages.error(request, 'Algunos datos en tu formulario estan incorrectos')
	menus = Menu.objects.filter(company = request.user.company)
	return render(request, 'app/menus.html',locals())

def menus_edit(request,slug, ide):
	menu = Menu.objects.filter(slug=slug, ide=ide, company = request.user.company)[0]
	form = MenusForm(instance = menu)
	if request.POST:
		form = MenusForm(request.POST, instance=menu)
		if form.is_valid():
			obj = form.save(commit = False)
			obj.company = request.user.company
			obj.save()
			messages.success(request, 'Modificado con éxito!')
			return HttpResponseRedirect( reverse('mis_menus' ) ) 
		else:
			messages.error(request, 'Algunos datos en tu formulario estan incorrectos')
	menu = Menu.objects.filter(slug=slug, ide=ide, company = request.user.company)[0]
	return render(request, 'app/menus_edit.html',locals())

def menus_delete(request,slug, ide):
	Menu.objects.filter(slug=slug, ide=ide, company = request.user.company)[0].delete()
	messages.warning(request, 'El menú se eliminó con exito')
	registry = Registry()
	registry.name = "Se eliminó menú"
	registry.code = "delete_menu"
	registry.user = request.user.user
	registry.company = request.user.company
	registry.save()
	return HttpResponseRedirect( reverse('menus') ) 

def sellpoints(request):
	form = Sell_pointForm()
	if request.method == "POST":
		if 'add_sell_point' in request.POST:
			form = Sell_pointForm(request.POST, request.FILES)
			if form.is_valid():
				points = len(Sell_point.objects.filter(company=request.user.company))
				if points >= request.user.company.sell_point_limits:
					messages.error(request, 'Llegaste al limite de tus puntos de venta')
				else:
					obj = form.save(commit=False)
					obj.company = request.user.company
					obj.create_by = request.user
					obj.save()
					messages.success(request, 'Nuevo punto de venta dado de alta con éxito')
			else:
				messages.error(request, 'Algunos datos en tu formulario estan incorrectos')
	pvs = Sell_point.objects.filter(company = request.user.company)
	return render(request, 'app/sellpoints.html',locals())

def sellpoints_edit(request, ide):
	sell_point = Sell_point.objects.filter(ide=ide)[0]
	form = Sell_pointForm(instance = sell_point)
	if request.POST:
		form = Sell_pointForm(request.POST, request.FILES, instance=sell_point)
		if form.is_valid():
			form.save()
			messages.success(request, 'Punto de venta modificado con éxito')
			return HttpResponseRedirect( reverse('mis_puntos_de_venta' ) ) 
		else:
			messages.error(request, 'Algunos datos en tu formulario estan incorrectos')
	return render(request, 'app/mis_puntos_de_venta_edit.html',locals())

def products(request):
	return render(request, 'app/products.html',locals())

def products_add(request):
	form = ProductForm()
	#if request.POST:
		#form = Sell_pointForm(request.POST, request.FILES)
		#if form.is_valid():
			#points = len(Sell_point.objects.filter(company=request.user.company))
			#if points >= request.user.company.sell_point_limits:
				#messages.error(request, 'Llegaste al limite de tus puntos de venta')
			#else:
				#obj = form.save(commit=False)
				#obj.company = request.user.company
				#obj.create_by = request.user
				#obj.save()
				#messages.success(request, 'Nuevo punto de venta dado de alta con éxito')
			#return HttpResponseRedirect( reverse('mis_puntos_de_venta' ) ) 
		#else:
			#messages.error(request, 'Algunos datos en tu formulario estan incorrectos')
	return render(request, 'app/products_add.html',locals())

	