from django.shortcuts import render
from django.template import loader
from django.urls import reverse
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User

from core.views import gen_page_base, gen_page_sys, get_get_value
from .forms import *
from .models import *
from .api import test_last_client_NUnic

def update(request):
	items = Baie.objects.all()
	for item in items:
		if item.BAIE_Site == "GENT":
			item.BAIE_Site = "GEN"
		item.save()
	# items = PIC.objects.all()
	# for item in items:
	# 	if item.PIC_L_Site == "GENT":
	# 		item.PIC_L_Site = "GEN"
	# 	if item.PIC_L_Statut == "OK":
	# 		item.PIC_L_Statut = "RAS"
	# 	item.save()
	return HttpResponse("OK")

@login_required(login_url='core_login')
def switch_show_list(request):
	template = loader.get_template('parc_info_switch_index.html')

	get_search = request.GET.get('get_search', '')
	get_id = request.GET.get('get_id', '')

	page = gen_page_base()

	if get_search :
		print(get_search)
		page.search = get_search
	if get_id :
		print(get_id)
		page.item_id = get_id

	page.p_adresse = reverse('parc_info_switch_show_list')
	page.p_titre = "Listing des Switchs"
	page.p_contenu = "Listing des Switch"
	page.p_right = "Les Outils :"
	
	html = template.render({
			'page': page,
			'user': request.user,
		}, request)
		
	return HttpResponse(html)

def switch_edit_info(request, id):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_switch_edit.html')

	if id == None or id == '0':
		item = Swich()
	else :
		item = Swich.objects.get(id = id)

	if request.method == 'POST':
		form = Edit_switch_form(request.POST, instance=item)
		if form.is_valid():
			form.save()
			get_value = "?get_id=" + str(item.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search

			return HttpResponseRedirect(reverse('parc_info_switch_show_list')+get_value)
	else:
		form = Edit_switch_form(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)

def switch_update_port(request, switch_id):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_switch_update.html')
	item = Swich.objects.get(id = switch_id)

	if request.method == 'POST':
		form = Update_switch_port(request.POST, instance=item)
		if form.is_valid():
			form.save()
			get_value = "?get_id=" + str(item.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search
			item = Swich.objects.get(id = switch_id)
			print (item)
			update = item.SW_Update_Port.splitlines()
			if item.SW_OS == "HP":
				for line in update:
					line_split = line.split()
					print (line_split[0], line_split[5], line_split[6:])
					if line_split[5] != "1":
						try:
							port = Port_Link.objects.filter(PL_Swich = item).get(PL_Port_NG = line_split[0])
							print("a mettre a jour")
						except:
							print("a crée")
							port = Port_Link(PL_Swich = item, PL_Port_NG = line_split[0])
						port.PL_VLAN = line_split[5]
						port.PL_Commentaires = ' '.join(line_split[6:])
						port.save()
			elif item.SW_OS == "CISCO":
				for line in update:
					line_split = line.split()
					print (line_split[0], line_split[3], line_split[1])
					try:
						port = Port_Link.objects.filter(PL_Swich = item).get(PL_Port_NG = line_split[0])
						print("a mettre a jour")
					except:
						print("a crée")
						port = Port_Link(PL_Swich = item, PL_Port_NG = line_split[0])
					port.PL_VLAN = line_split[3]
					port.PL_Commentaires = line_split[1]
					port.save()
			elif item.SW_OS == "ARUBA":
				for line in update:
					line_split = line.split()
					if line_split[2] == "Down" or line_split[2] == "Up":
						print (line_split[0], line_split[7], line_split[1])
						try:
							port = Port_Link.objects.filter(PL_Swich = item).get(PL_Port_NG = line_split[0])
							print("a mettre a jour")
						except:
							print("a crée")
							port = Port_Link(PL_Swich = item, PL_Port_NG = line_split[0])
						port.PL_VLAN = line_split[7]
						port.PL_Commentaires = line_split[1]
						port.save()


			item.SW_Update_Port = None
			item.save()
			return HttpResponseRedirect(reverse('parc_info_switch_show_list')+get_value)
	else:
		form = Update_switch_port(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)


def switch_edit_port(request, switch_id, port_id):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_switch_port.html')

	if port_id == None or port_id == '0':
		item = Port_Link()
		item.PL_Swich = Swich.objects.get(id = switch_id)
	else :
		item = Port_Link.objects.get(id = port_id)

	if request.method == 'POST':
		form = Edit_switch_port_form(request.POST, instance=item)
		if form.is_valid():
			form.save()
			get_value = "?get_id=" + str(item.PL_Swich.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search
			return HttpResponseRedirect(reverse('parc_info_switch_show_list')+get_value)
	else:
		form = Edit_switch_port_form(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)

@login_required(login_url='core_login')
def srv_show_list(request):
	template = loader.get_template('parc_info_srv_index.html')

	get_search = request.GET.get('get_search', '')
	get_id = request.GET.get('get_id', '')

	page = gen_page_base()

	if get_search :
		print(get_search)
		page.search = get_search
	if get_id :
		print(get_id)
		page.item_id = get_id

	page.p_adresse = reverse('parc_info_srv_show_list')
	page.p_titre = "Listing des serveurs"
	page.p_contenu = "Listing des serveur présent dans le parc informatique"
	page.p_right = "Les Outils :"
	
	html = template.render({
			'page': page,
			'user': request.user,
		}, request)
		
	return HttpResponse(html)

def srv_edit_info(request, id_srv):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_srv_edit.html')

	if id_srv == None or id_srv == '0':
		item = PIS()
	else :
		item = PIS.objects.get(id = id_srv)
	#print(item)
	if request.method == 'POST':
		form = Edit_srv_form(request.POST, instance=item)
		if form.is_valid():
			form.save()
			get_value = "?get_id=" + str(item.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search
			return HttpResponseRedirect(reverse('parc_info_srv_show_list')+get_value)
	else:
		form = Edit_srv_form(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)

@login_required(login_url='core_login')
def user_show_list(request):
	template = loader.get_template('parc_info_user_index.html')

	get_search = request.GET.get('get_search', '')
	get_id = request.GET.get('get_id', '')

	page = gen_page_base()
	if get_search :
		print(get_search)
		page.search = get_search
	if get_id :
		print(get_id)
		page.item_id = get_id
	
	page.p_adresse = reverse('parc_info_user_show_list')
	page.p_titre = "Listing des équipements utilisateurs"
	page.p_contenu = "Listing des équipements utilisateurs présent dans le parc informatique"
	page.p_right = "<h3>Menu</h3><p><a href='/parc/clients/enstock'>Listing des équipements en stock</a><br><a href='/parc/clients/aprep'>Listing des équipements en préparation</a><br><a href='/parc/clients/deprod'>Listing des équipements en inapt</a></p><h3>Les Outils</h3>"
	page.search_see = "ok"

	services = Services.objects.all()
	
	html = template.render({
			'page': page,
			'user': request.user,
			'services': services,
		}, request)
		
	return HttpResponse(html)

def user_edit_info(request, id_user):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_user_edit.html')

	if id_user == None or id_user == '0':
		item = PIC()
	else :
		item = PIC.objects.get(id = id_user)

	if request.method == 'POST':
		form = Edit_user_mini_form(request.POST, instance=item)
		if form.is_valid():
			form.save()
			item = PIC.objects.get(id = item.id) #Update Value
			if item.PIC_Nom_netbios == None and item.PIC_NUnic == None :
				item.PIC_Nom_netbios = item.PIC_L_Site + "-"
				
				if item.PIC_L_Chassi_Type != "IMP":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + item.PIC_L_Service.SERVICE_Anag + "-"
				
				if item.PIC_L_Chassi_Type == "PC":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "W"
					item.PIC_NUnic = test_last_client_NUnic("PC")
				elif item.PIC_L_Chassi_Type == "PORTABLE":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "L"
					item.PIC_NUnic = test_last_client_NUnic("PC")
				elif item.PIC_L_Chassi_Type == "CL":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "T"
					item.PIC_NUnic = test_last_client_NUnic("PC")
				elif item.PIC_L_Chassi_Type == "PANEL-PC":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "D"
					item.PIC_NUnic = test_last_client_NUnic("PC")
				elif item.PIC_L_Chassi_Type == "IMP":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "P"
					item.PIC_NUnic = test_last_client_NUnic("IMP")
				
				item.PIC_Nom_netbios = item.PIC_Nom_netbios + str(item.PIC_NUnic).zfill(4)

				print(item.PIC_NUnic)
				print(item.PIC_Nom_netbios)
				item.save()

			elif item.PIC_Nom_netbios == None:
				item.PIC_Nom_netbios = item.PIC_L_Site + "-"
				
				if item.PIC_L_Chassi_Type != "IMP":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + item.PIC_L_Service.SERVICE_Anag + "-"
				
				if item.PIC_L_Chassi_Type == "PC":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "W"
				elif item.PIC_L_Chassi_Type == "PORTABLE":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "L"
				elif item.PIC_L_Chassi_Type == "CL":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "T"
				elif item.PIC_L_Chassi_Type == "PANEL-PC":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "D"
				elif item.PIC_L_Chassi_Type == "IMP":
					item.PIC_Nom_netbios = item.PIC_Nom_netbios + "P"
				
				item.PIC_Nom_netbios = item.PIC_Nom_netbios + str(item.PIC_NUnic).zfill(4)

				print(item.PIC_NUnic)
				print(item.PIC_Nom_netbios)
				item.save()

			get_value = "?get_id=" + str(item.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search

			return HttpResponseRedirect(reverse('parc_info_user_show_list')+get_value)
	else:
			form = Edit_user_mini_form(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)

def user_edit_statut(request, id_user):
	get_search = request.GET.get('get_search', '')

	template = loader.get_template('parc_info_user_statut.html')

	if id_user == None or id_user == '0':
		item = PIC()
	else :
		item = PIC.objects.get(id = id_user)
	#print(item)
	if request.method == 'POST':
		form = Edit_user_statut_form(request.POST, instance=item)
		if form.is_valid():
			form.save()
			get_value = "?get_id=" + str(item.id)
			if get_search:
				get_value = get_value + '&get_search=' + get_search
			return HttpResponseRedirect(reverse('parc_info_user_show_list')+get_value)
	else:
			form = Edit_user_statut_form(instance=item)

	html = template.render({
			'form': form,
			'item': item,
		}, request)
		
	return HttpResponse(html)

@login_required(login_url='core_login')
def user_show_list_en_stock(request):
	
	template = loader.get_template('parc_info_user_index.html')
	page = gen_page_base()
	page.p_adresse = reverse('parc_info_user_show_list_en_stock')
	page.p_titre = "Liste des matériels en STOCK"
	page.p_contenu = "Liste des matériels en STOCK"
	page.p_right = "&nbsp"
	page.p_include = "parc_info_api_user_get_list.html"
	
	data_query =  PIC.objects.filter(PIC_L_Statut = 'EN STOCK').exclude(PIC_L_Chassi_Type = 'IMP' ).order_by('PIC_NUnic')
	
	html = template.render({
			'page': page,
			'data_query':data_query,
			'user': request.user,
		}, request)
	return HttpResponse(html)

@login_required(login_url='core_login')
def user_show_list_aprep(request):
	
	template = loader.get_template('parc_info_user_index.html')
	page = gen_page_base()
	page.p_adresse = reverse('parc_info_user_show_list_en_stock')
	page.p_titre = "Liste des matériels encours de préparation"
	page.p_contenu = "Liste des matériels encours de préparation"
	page.p_right = "&nbsp"
	page.p_include = "parc_info_api_user_get_list.html"
	
	data_query =  PIC.objects.filter(PIC_L_Statut = 'PREPROD').exclude(PIC_L_Chassi_Type = 'IMP' ).order_by('PIC_NUnic')
	
	html = template.render({
			'page': page,
			'data_query':data_query,
			'user': request.user,
		}, request)
	return HttpResponse(html)

@login_required(login_url='core_login')
def user_show_list_deprod(request):
	
	template = loader.get_template('parc_info_user_index.html')
	page = gen_page_base()
	page.p_adresse = reverse('parc_info_user_show_list_deprod')
	page.p_titre = "Liste des matériels en plus en service"
	page.p_contenu = "Liste des matériels en plus en service"
	page.p_right = "<p>Liste des matériels plus en service car celui-ci est HS ou n'est pour adapté au besoin actuel.</p>"
	page.p_include = "parc_info_api_user_get_list.html"
	
	data_query =  PIC.objects.filter(PIC_L_Statut = 'INAPTE').exclude(PIC_L_Chassi_Type = 'IMP' ).order_by('PIC_NUnic')
	
	html = template.render({
			'page': page,
			'data_query':data_query,
			'user': request.user,
		}, request)
	return HttpResponse(html)

@login_required(login_url='core_login')
def user_show_list_imp(request):
	
	template = loader.get_template('parc_info_user_index.html')
	page = gen_page_base()
	page.p_adresse = reverse('parc_info_user_show_list_imp')
	page.p_titre = "Liste des imprimantes"
	page.p_contenu = "Liste des imprimantes"
	page.p_right = "&nbsp"
	page.p_include = "parc_info_api_user_get_imp.html"
	
	data_query = PIC.objects.filter(PIC_L_Chassi_Type = 'IMP').order_by('PIC_L_Site','PIC_L_Service__SERVICE_Nom','PIC_NUnic')
	
	html = template.render({
			'page': page,
			'data_query':data_query,
			'user': request.user,
		}, request)
	return HttpResponse(html)

@login_required(login_url='core_login')
def stat_user_by_service(request):
	page = gen_page_base()
	template = loader.get_template('parc_info_stat_user_by_service.html')

	items =  PIC.objects.exclude(PIC_L_Statut__in = ['INAPTE', 'EN STOCK']).exclude(PIC_L_Chassi_Type = 'IMP' ).order_by('PIC_L_Site','PIC_L_Service__SERVICE_Nom')
	items_imp = PIC.objects.exclude(PIC_L_Statut__in = ['INAPTE', 'EN STOCK']).filter(PIC_L_Chassi_Type = 'IMP' ).order_by('PIC_L_Site','PIC_L_Service__SERVICE_Nom')

	for item in items:
		item.accessoir = Accessory_Link.objects.filter(pic = item)

	html = template.render({
		'items': items,
		'items_imp': items_imp,
		'page': page,
	}, request)
		
	return HttpResponse(html)

@login_required(login_url='core_login')
def stat_user_without_snow(request):
	page = gen_page_base()
	template = loader.get_template('parc_info_stat_user_without_snow.html')

	item =  PIC.objects.exclude(PIC_L_Statut__in = ['INAPTE', 'EN STOCK']).filter(PIC_L_Chassi_Type__in = ['PC','PORTABLE','PANEL-PC']).filter(PIC_with_Snow = False).order_by('PIC_L_Site','PIC_L_Service__SERVICE_Nom')

	html = template.render({
		'item': item,
		'page': page,
	}, request)
		
	return HttpResponse(html)

def import_snow_data(request):

	import openpyxl
	workbook = openpyxl.load_workbook(filename='./static/import/ComputersList.xlsx', read_only=True)
	
	first_sheet = workbook.get_sheet_names()[0]
	worksheet = workbook.get_sheet_by_name(first_sheet)

	for row in worksheet.iter_rows():

		tmp_Nom_netbios = str(row[0].value)
		print(tmp_Nom_netbios)
		need_update = 0
		try :
			item = PIC.objects.exclude(PIC_L_Statut__in = ['INAPTE', 'EN STOCK']).get(PIC_Nom_netbios = tmp_Nom_netbios)
			print("PC > ok exist")
			need_update = 1
		except:
			try : 
				item = PIS.objects.exclude(PIS_Archive = True).get(PIS_Nom_netbios = tmp_Nom_netbios)
				print("SRV > ok exist")
				need_update = 2
			except:
				pass
		
		if need_update == 1:
			item.PIC_with_Snow = True
			item.PIC_Adresse_IP = str(row[1].value)
			item.PIC_Marque = str(row[2].value)
			item.PIC_Type = str(row[3].value)
			item.PIC_OS = str(row[5].value)
			item.PIC_SN = str(row[12].value)
			tmp_Utilisateur = str(row[8].value)

			tmp_Utilisateur = tmp_Utilisateur.split( )
			try :
				tmp_sp_tmp_Utilisateur = tmp_Utilisateur[-1]
				tmp_sp_tmp_Utilisateur = tmp_sp_tmp_Utilisateur.replace('\\', '').replace('(STJACQUES', '').replace(')', '')
				item.PIC_Utilisateur_Fq = tmp_sp_tmp_Utilisateur
			except :
				pass

			tmp_PIC_CPU = str(row[9].value)
			tmp_PIC_CPU = tmp_PIC_CPU.split(' @')
			item.PIC_CPU = tmp_PIC_CPU[0]
			item.PIC_CPU = item.PIC_CPU.replace(' CPU', '').replace('11th Gen ', '')
			item.PIC_RAM = int(float(row[11].value / 1024))

			item.save()

		elif need_update == 2:
			item.PIS_with_Snow = True
			item.PIS_Adresse_IP = str(row[1].value)
			if str(row[2].value) == "VMware, Inc.":
				item.PIS_Type = "MACHINE VIRTUELLE"
				item.PIS_CPU = str(row[10].value)
			else:
				item.PIS_Type = str(row[2].value)
				item.PIS_SN = str(row[12].value)
				tmp_PIS_CPU = str(row[9].value)
				tmp_PIS_CPU = tmp_PIS_CPU.split(' @')
				item.PIS_CPU = tmp_PIS_CPU[0]
				item.PIS_CPU = item.PIS_CPU.replace(' CPU', '').replace('11th Gen ', '')

			item.PIS_OS = str(row[5].value)
			
			item.PIS_RAM = int(float(row[11].value / 1024))

			item.save()

	return HttpResponse("ok")