from django.shortcuts import render
import os4l.models as mo
from django.http import HttpResponse
import json
import os
from django.utils.translation import gettext as _
from django.utils.translation import get_language, activate
import pandas as pd

import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from fpdf import FPDF, HTMLMixin

from django.middleware.csrf import get_token
from django.views.decorators.http import require_GET
from django.http import JsonResponse
from datetime import datetime
import time
from django.contrib.auth.decorators import login_required
# Create your views here.


def index(request):
	if request.method =='POST':
		email = request.POST["email"]
		args = mo.JourneyEntry.objects.all().order_by('journeyid')
		args = args.exclude(online=False)	
		mo.Subsriber.objects.create(subid = 1, name=" ",email=email)
		return render(request,'index.html',{'entries':args, 'stick':args, 'page':pages})

	else:
		args = mo.JourneyEntry.objects.all().order_by('journeyid')
		args = args.exclude(online=False)
		pages = mo.Pages.objects.get(name="Landingpage")

		return render(request,'index.html',{'entries':args, 'stick':args, 'page':pages})

def contact(request):
	stick = mo.JourneyEntry.objects.all().order_by('journeyid')
	stick = stick.exclude(online=False)
	return render(request,'contact.html',{'stick':stick})

def about(request):
	args = mo.Team.objects.all().order_by('teamid')
	args = args.exclude(online=False)

	co = mo.Kooperation.objects.all().order_by('koopid')
	co = co.exclude(online=False)

	stick = mo.JourneyEntry.objects.all().order_by('journeyid')
	stick = stick.exclude(online=False)
	return render(request,'about.html', {'entries':args,'kollab':co,'stick':stick})

def faq(request):
	args = mo.FAQ.objects.all().order_by('faqid')
	args = args.exclude(online=False)

	stick = mo.JourneyEntry.objects.all().order_by('journeyid')
	stick = stick.exclude(online=False)
	return render(request,'faq.html', {'entries':args,'stick':stick})

def join(request):
	if request.method =='POST':
		email = request.POST["email"]
		stick = mo.JourneyEntry.objects.all().order_by('journeyid')
		stick = stick.exclude(online=False)
		mo.Subsriber.objects.create(subid = 1, name=" ",email=email)
		return render(request,'join.html', {'stick':stick})



	else:
		stick = mo.JourneyEntry.objects.all().order_by('journeyid')
		stick = stick.exclude(online=False)
		return render(request,'join.html', {'stick':stick})

def subscribe(request):
	stick = mo.JourneyEntry.objects.all().order_by('journeyid')
	stick = stick.exclude(online=False)
	return render(request,'subscribe.html', {'stick':stick})

def simulator(request):
	if request.method == 'POST':
		data = request.POST["answers"]
		data = data.split(",")
		for i in range(len(data)):
			if data[i] == "*":
				data[i] = None


		# Data to be written
		dictionary = {
			"stichtype": data[0],
			"size": data[1],
		}
		 
		# Serializing json
		json_object = json.dumps(dictionary, indent=4)
		 
		# Writing to sample.json
		with open("sample.json", "w") as outfile:
			outfile.write(json_object)

		return render(request,'simulator.html')

	else:
		return render(request,'simulator.html')



def care(request):
	args = mo.Care.objects.all().order_by('-id')
	args = args.exclude(online=False)
	return render(request,'care.html', {'entries':args})


def content(request):
	if request.method =='GET':
		Title = request.GET.get["Title"]
		args = mo.Care.objects.get(slug=Title)
		return render(request, 'content.html',{'entries':args})

	else:
		return HttpResponse("That Sucks")

link = "report/"
link = "/var/www/html/os4al/main/media/" #Uncomment in production_________________________________________________________________________________________




def mail(request):
	print(request)
	if request.method =='POST':
		print("I recieved a Post request")
		json_file = request.FILES.get('json_data')


		if json_file:
			json_data = json_file.read().decode('utf-8')
			data = json.loads(json_data)

		# Accessing the uploaded images

		print("I got the json file")
		stored_images = []
		images = request.FILES.getlist('images')
		if images:
			for i, image in enumerate(images):
				# Process each image as needed
				current_time = datetime.now()
				identifier = current_time.strftime("%Y%m%d_%H%M%S")
				file_name = link + f"report/images/woolreport_" + identifier + ".png"
				time.sleep(1)
				with open(file_name, 'wb') as f:
					f.write(image.read())

				stored_images.append(file_name)


		pdf_path = create_pdf(data,stored_images)
		mo.Subsriber.objects.create(email=data['email'], name=data['name'], surname= data['surname'], report=pdf_path)
		tls(data['email'],link + pdf_path)
		return HttpResponse("all info recevied")



	if request.method == 'GET':
		csrf_token = get_token(request)
		response = JsonResponse({'csrftoken': csrf_token})
		response.set_cookie('csrftoken', csrf_token, httponly=False, samesite='Lax')  # Adjust other parameters as necessary
        
		print("CSRF Token:", csrf_token) 
		print("Response Headers:", response.items())
		return response


# 

def tls(adress, filepath):
	port = 587  # For starttls
	smtp_server = "mail.privateemail.com"
	sender_email = "contact@onesheepforalifetime.com"
	receiver_email = adress
	password = "Schaf3gal!"
	subject = "Your Wool Report is ready."
	body = """Hello dear sheep friend!

We are happy you tried out our Sheep's Wool Simulator :D

Find your personal wool report in the attachment. It gives you an overview of how you set your 1000 grams of sheep's wool to a purpose.

Our platform and tools are still in development, so stay tuned for more ;)

Wooly regards,
the One Sheep Team
	"""

	# Create a multipart message and set headers
	message = MIMEMultipart()
	message["From"] = "One Sheep <contact@onesheepforalifetime.com>"
	message["To"] = receiver_email
	message["Subject"] = subject
		
	# Add body to email
	message.attach(MIMEText(body, "plain"))

	# Open PDF file in binary mode
	with open(filepath, "rb") as attachment:
		# Add file as application/octet-stream
		# Email client can usually download this automatically as attachment
		part = MIMEBase("application", "octet-stream")
		part.set_payload(attachment.read())

	# Encode file in ASCII characters to send by email    
	encoders.encode_base64(part)
	filename = "Woolreport.pdf"

	# Add header as key/value pair to attachment part
	part.add_header(
		"Content-Disposition",
		f"attachment; filename= {filename}",
	)

	# Add attachment to message and convert message to string
	message.attach(part)
	text = message.as_string()

		# Log in to server using secure context and send email
	context = ssl.create_default_context()
	with smtplib.SMTP(smtp_server, port) as server:
		server.ehlo()  # Can be omitted
		server.starttls(context=context)
		server.ehlo()  # Can be omitted
		server.login(sender_email, password)
		server.sendmail(sender_email, receiver_email, text)

class PDF(FPDF, HTMLMixin):
	pass

def create_pdf(data, images):
	print(images)

	debug = 0
	garments = data['garments']

	print(data['name'])
	print(type(data['name']))


	if data['name'] == "":
		name = "Your"

	else:
		name =  data['name'] + " 's"


	used_wool = str(round(data['total_used_wool_g'],0))
	leftover_wool = str(round(data['total_used_wool_m'],0))

	h = 14
	sh = 10
	p = 8


	width = 57
	image_width = width - 8
	height = 104 + len(garments) * 90
	
	pdf =  PDF('P', 'mm', (width, height))
	pdf.add_page()
	pdf.set_margins(4.5,0,4.5)
	pdf.set_font("Arial", size = h)
	
	pdf.set_font("Arial", size = h, style="B")
	pdf.cell(0,1, txt= "", border=debug, align="C", ln=1)
	pdf.cell(0,5, txt= name, border=debug, align="C", ln=1)
	pdf.cell(0,5, txt= "Wool Report", border=debug, align="C", ln=1)
	pdf.set_font("Arial", size = p, style="")
	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.cell(0,5, txt= "*****************************************",border= debug,align="C",ln=1)

	
	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.set_font("Arial", style="BU", size = sh)
	pdf.cell(0,5, txt= "Wool used",  border=debug, align="C",ln=1)
	pdf.set_font("Arial", size = p)
	pdf.cell(0,5, txt= used_wool + " grams" , border=debug, align="C",ln=1)


	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.set_font("Arial", size = sh, style="BU" ) 
	pdf.cell(0,5, txt= "Wool donated",border=debug, align="C",ln=1)
	pdf.set_font("Arial", size = p)
	pdf.cell(0,5, txt= leftover_wool + " grams" , border=debug, align="C",ln=1)
	pdf.cell(0,5, txt= "" , border=debug, align="C",ln=1)
	
	pdf.set_font("Arial", size = p, style="")
	pdf.cell(0,5, txt= "*****************************************",border= debug,align="C",ln=1)

	for i, garment in enumerate(garments):
		pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
		pdf.set_font("Arial", size = sh, style="B" )
		pdf.cell(0,5, txt= str(garment['garment_name']), border=debug, align="C",ln=1)
		pdf.set_font("Arial", size = p)

		# Add image for the garment
		if i < len(images):  # Ensure we have an image for this garment
			image_path = images[i]
			# Calculate the x position to center the image
			x_position = (width - image_width) / 2
			# Insert image below the garment details, centered
			pdf.cell(0, 5, txt=" ", border=debug, align="C", ln=1)
			pdf.image(image_path, x=x_position, w=image_width)  # Center the image

		pdf.cell(0,5, txt= str(garment['garment_wool_g']) + " grams" , border=debug, align="C",ln=1)
		pdf.cell(0,5, txt= str(garment['garment_stichtype']) , border=debug, align="C",ln=1)
		pdf.cell(0,5, txt= str(garment['garment_tension']) , border=debug, align="C",ln=1)
		pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
		pdf.cell(0,5, txt= "*****************************************",border= debug,align="C",ln=1)    


	pdf.cell(0,10, txt= "onesheepforalifetime.com",border= debug,align="C",ln=1)
	pdf.set_font("Arial", size = p)
	current_time = datetime.now()
	identifier = current_time.strftime("%Y%m%d_%H%M%S")
	fpath = "media/report/" + identifier + "_woolreport.pdf"
	
	fpath = "/var/www/html/os4al/main/media/report/" + identifier + "_woolreport.pdf" #uncomment when going for production
	
	pdf.output(fpath)
	
	fpath = "report/" + identifier + "_woolreport.pdf"
	return fpath


#______________DEPRICATED REMOVE WHEN SURE
#def report(request):
# 	if request.method =='POST':
# 		print("i recieved a post request")

# 	if request.method =='GET':

# 		content = request.GET['report']

# 		data = content[1:]
# 		data = data[:-1]
# 		data = data.split(",")
# 		save_report(data)

# 		#------------------------------------------------- Printer Function below
# 		count = 0
# 		dir_path = link;
# 		for path in os.scandir(dir_path):
# 				if path.is_file():
# 					count += 1

# 		count = count + 1
# 		name =  str(count)
# 		name =  name.rjust(6,'z') + ".json"
# 		f = open(link + name, "w")
# 		f.write(content)
# 		f.close()

# 		f = open(link + "000000"+ ".json", "w")
# 		f.write(content)
# 		f.close()

# 		return HttpResponse("yay")

# 	else:
# 		return HttpResponse("something went wrong")

# def save_report(data):
# 		mo.Subsriber.objects.create(subid = 1, email=data[1], name=data[2], surname= data[3])

# 		report = []
# 		for i in range(6):
# 			report.append(data[0])
# 			data.pop(0)

# 		garments = []
# 		for i in range(len(data)):
# 			garments.append(data[i])

# 		garments = str(garments)
# 		garments = garments[1:-1]
# 		report.append(garments)

# 		csv = pd.read_csv("/var/www/html/os4al_web/main/report/reports.csv")
# 		#csv = pd.read_csv("report/reports.csv")
# 		csv.loc[len(csv)] = report
# 		csv.to_csv("/var/www/html/os4al_web/main/report/reports.csv", index=False)
# 		#csv.to_csv("report/reports.csv")





		#data = json.loads(request.body.decode('utf-8'))
		#print("Received JSON data:", data)
		#mail = request.POST[]
		#mail = mail[1:]
		#mail = mail[:-1]
		#mail = mail.split(",")
		#adress = mail[1]
		#save_report(mail)
		#create_pdf()