import asyncio
from concurrent.futures import ThreadPoolExecutor
from typing import Optional

from aiofauna import FaunaModel
from boto3 import Session
from pydantic import Field  # pylint: disable=E0611

from ..config import AWSCredentials
from ..schemas import *

credentials = AWSCredentials().dict()

aws = Session(**credentials)

ses = aws.client("ses")


class ContactForm(FunctionDocument, FaunaModel):
	"""Fills a contact form for a user in order to suscribe to a newsletter,
	offers, premium content or custommer support. Must validate the email
	characters, verifies the email on SES and if it's not verified it will
	send a verification email"""

	name: str = Field(..., max_length=64, description="Name of the user.",index=True)
	email: str = Field(...,description="Email of the user.",index=True)
	message: Optional[str] = Field(default=None, description="Message of the user. If None, it will be autogenerated.")
	verified: bool = Field(default=False, description="If the email is verified.",index=True)

	def send_email_ses(self):
		response = ses.send_email(
			Source="oscar.bahamonde.dev@gmail.com",
			Destination={"ToAddresses": [self.email]},
			Message={
				"Subject": {"Data": "Welcome to AioFauna"},
				"Body": {
					"Text": {
						"Data": f"Hello {self.name},\n\nThank you for contacting us. We will get back to you as soon as possible.\n\nBest regards,\nOscar Bahamonde",
					}
				},
			},
		)
		return response
	
	@process_time
	@handle_errors
	async def run(self):
		identities = ses.list_identities()
		if self.email not in identities["Identities"]:
			ses.verify_email_identity(EmailAddress=self.email)
			self.verified = False
			await self.save()
		else:
			self.verified = True
			response = await asyncio.to_thread(self.send_email_ses)
			if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
				return await self.save()
			else:
				raise RuntimeError(response)
