<script lang="ts">
	import { userStore } from '$lib/UserStore.svelte';
	import { get } from '$lib/utils';
	import { onMount, onDestroy } from 'svelte';
	import Pill from './pill.svelte';

	let id: string | undefined | null = $state(undefined);

	onMount(() => {
		const url = new URLSearchParams(window.location.search);
		id = url.get('id');
		loadData();
	});

	type SimpleFlair = {
		name: string;
		description: string;
		color: string;
		sort: number;
		showFullDescription: number;
	};

	type Application = {
		recruiter: string;
		message: string;
		company: string;
		agency: boolean;
		flairs: SimpleFlair[];
	};

	let application: Application | undefined = $state(undefined);

	async function loadData() {
		if (!id) return;
		try {
			application = await get(`application/cv/${id}`);

			if (!application) {
				return;
			}

			application.flairs.sort((a, b) => {
				const aDesc = a.description && a.showFullDescription === 1;
				const bDesc = b.description && b.showFullDescription === 1;

				if (aDesc && bDesc) {
					return b.sort - a.sort;
				}
				if (aDesc) {
					return -1;
				}
				if (bDesc) {
					return 1;
				}
				return b.sort - a.sort;
			});

			await loadFlairs();
		} catch (e) {
			console.log('TODO show this to the user', e);
		}
	}

	// Other skills search
	let otherSearch = $state('');
	let flairs: SimpleFlair[] = $state([]);

	async function loadFlairs() {
		try {
			flairs = await get(`flair/simple/${id ?? ''}`);
		} catch (e) {
			console.log('TODO inform the user', e);
		}
	}

	let rootEml: HTMLDivElement;

	function getDPI() {
		var div = document.createElement('div');
		div.style.height = '1in';
		div.style.width = '1in';
		div.style.top = '-100%';
		div.style.left = '-100%';
		div.style.position = 'absolute';

		document.body.appendChild(div);

		var result = div.offsetHeight;

		document.body.removeChild(div);

		return result;
	}

	function onPrint() {
		const dpi = getDPI();
		function cmToPx(cm: number) {
			return cm * 0.3937 * dpi;
		}
		const padding = 20;
		// A4 is 29.7
		const pageHeight = Math.floor(cmToPx(29.7));

		// This will be used for comparansions so we allow the starting padding
		const limitedPageHeight = pageHeight - padding;

		const children = rootEml.children;

		let page = 0;

		// As we had padding it will not right away update the dom so we need to account for that
		// this will keep track of that
		let extraHeight = 0;

		for (let i = 0; i < children.length; i++) {
			const elm = children[i];
			// console.log('here', elm);
			const box = elm.getBoundingClientRect();

			const useHeight = elm.getAttribute('data-useheight')
				? Number(elm.getAttribute('data-useheight'))
				: null;
			if (useHeight !== null) {
				extraHeight += useHeight - box.height;
			}

			const end = box.top + box.height + extraHeight;

			// console.log(page, page * pageHeight + limitedPageHeight, end, extraHeight);
			if (page * pageHeight + limitedPageHeight < end) {
				// console.log('Goes over recalculating', elm);
				// Find the autoPadding
				for (let j = i - 1; j > 0; j--) {
					const s = children[j];
					if (s.getAttribute('data-autopad') !== null) {
						// console.log('found autoPadding', s);
						const start = s.getBoundingClientRect().top + extraHeight;
						const distToEnd = Math.ceil(pageHeight - (start - page * pageHeight));
						(s as any).style.setProperty('--auto-size', `${distToEnd + padding}px`);
						// console.log('padding with', distToEnd + padding);
						extraHeight += distToEnd + padding;
						page += 1;
						break;
					}
				}
			}
		}
	}

	onMount(() => {
		window.addEventListener('beforeprint', onPrint);
	});

	onDestroy(() => {
		window.removeEventListener('beforeprint', onPrint);
	});
</script>

<svelte:head>
	{#if application && userStore.isLoggedIn}
		<title>
			andre-henriques-{application.company.toLowerCase().split(' ')[0]}
		</title>
	{:else}
		<title>CV</title>
	{/if}
</svelte:head>

<div class="flex items-center w-full flex-col" bind:this={rootEml}>
	<div class="py-5 pb-0 w-[190mm] print:py-0 print:pt-4" data-useheight="228">
		<div class="bg-white rounded-lg p-3">
			<div class="w-full flex">
				<h1 class="text-black text-5xl">Andre Henriques</h1>
				<div class="flex-grow"></div>
				<div class="text-right">
					<ul>
						<li class="px-1">
							{#if id}
								<a
									class="underline"
									href="https://www.andr3h3nriqu3s.com/cv?id={id}"
									>andr3h3nriqu3s.com</a
								>
							{:else}
								<a class="underline" href="https://www.andr3h3nriqu3s.com/cv"
									>andr3h3nriqu3s.com</a
								>
							{/if}
						</li>
						<li class="px-1">
							<a class="underline" href="mailto:contact@andr3h3nriqu3s.com"
								>contact@andr3h3nriqu3s.com</a
							>
						</li>
						<li class="px-1">
							<a class="underline" href="tel:+4407823391342">+44 0 782339 1342</a>
						</li>
					</ul>
				</div>
			</div>
			<div class="w-full flex py-3 print:pb-0">
				<div>
					I am a dedicated and versatile programmer with four years of professional
					experience. <br />
					During those years mainly worked with Typescript, JavaScript, React, Svelte.
					<br />
					I thrive in high paced new environments, and I am always striving to learn new skills
					and technologies.
					<br />
					I also am knowable in various other technologies and am always learning new ones.
					<br />
				</div>
			</div>
		</div>
	</div>

	{#if application}
		{#if !application.agency}
			<h2 class="text-white p-6 print:p-0 text-4xl print:text-3xl" data-useheight="36">
				👋 Hello
				{#if application.recruiter}
					<span class="font-bold">{application.recruiter}</span> @
					<span class="font-bold">{application.company}</span>
				{:else if application.company}
					recruiter @ <span class="font-bold">{application.company}</span>
				{/if}
			</h2>
		{:else}
			<div class="p-5 print:hidden"></div>
		{/if}

		{#if application.message}
			<div class="p-3 bg-white w-[190mm] rounded-lg">
				<h1>Why your role interests me</h1>
				<div class="py-2">
					{@html application.message.split('\n').join('<br>')}
				</div>
			</div>
			<div class="p-1"></div>
		{/if}
	{:else}
		<div class="p-1"></div>
	{/if}

	<div class="w-[190mm]" data-useheight="32">
		<h2
			class="p-3 pt-0 print:p-0 text-4xl print:text-2xl font-bold print:font-normal text-white"
		>
			Work Expericence
		</h2>
	</div>

	<div class="w-[100vw] flex items-center flex-col" data-useheight="340">
		<div class="p-3 print:p-0 bg-white w-[190mm] rounded-lg">
			<h1>Senior Software Engineer @ Planum Solucoes</h1>
			<h2>4 years - May 2020 - Present</h2>
			<div class="ml-3">
				My role is mainly focused on frontend development, while also having a supporting
				role with the API and DevOps teams.
				<ul class="pl-5 list-disc">
					<li>
						Main developer for frontend on the core platform, and the derivative
						products, such as video call app for doctors, video call app for vets,
						timesheets management, budget management, stock management, gambling
						monitoring platform, survey platform, file sharing platform, issue tracking
						platform.
					</li>
					<li class="ml-4">
						<b>Stack</b>: Frontend (React, Typescript, Tailwind); Backend (Java, Spring
						boot, Kafka); Infrastructure (Docker, AWS, Nginx).
					</li>
					<li>
						Championed and Led a move for the use of CI/CD pipelines for deployment
						using Docker on AWS, and started to introduce better testing.
					</li>
					<li>
						Support any other team with any problem that might arise, for example
						deploying a Kafka cluster or modifying a python CLI tool.
					</li>
				</ul>
			</div>
		</div>
	</div>

	<div class="p-2 print:p-1" data-useheight="4"></div>

	<div class="w-[100vw] flex items-center flex-col" data-useheight="268">
		<div class="text-black w-[190mm] bg-white p-4 print:p-0 rounded-lg">
			<div>
				<div>
					<h1>Associate DevOps Engineer @ Sky</h1>
					<h2>1 year: July 2022–June 2023</h2>
					<div class="ml-3">
						My time at sky was split into two roles. One role involved maintaining
						existing data and file pipelines, using Jenkins, Bash, and Python. My second
						role was full-stack development, where I maintained and upgraded existing
						applications and developed new ones, mostly with Python and Flask.
						<ul class="pl-5 list-disc">
							<li>
								Maintained and updated and webapp that is used daily to monitor
								various systems that the team looks after.
							</li>
							<li>
								Created new backup, and rapid deployment solutions for Jenkins
								servers.
							</li>
							<li>
								Fixed, updated, and created new pipelines that were able to erase
								terabytes of redundant data, improving performance of other
								pipelines and the backup system.
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="p-1"></div>

	<div class="autoPadding" data-autopad></div>

	<div class="w-[190mm]" data-useheight="28">
		<h2 class="p-3 print:p-0 text-4xl print:text-xl font-bold print:font-normal text-white">
			Education
		</h2>
	</div>
	<div class="bg-white p-2 text-black rounded-lg w-[190mm] print:text-sm">
		<div>
			<div>
				<h1>BSc Computer Science @ University of Surrey</h1>
				<div class="ml-2 flex justify-between">
					<h2>July 2020 - June 2024</h2>
				</div>
			</div>
		</div>
	</div>

	<div class="p-1"></div>

	<div class="autoPadding" data-autopad></div>

	{#if application}
		{#if application.flairs.length > 0}
			<div class="w-[190mm]">
				<h2
					class="p-3 print:p-0 text-4xl print:text-xl font-bold print:font-normal text-white flex gap-2 items-center"
				>
					Skills {#if flairs.length > 0}<input
							placeholder="Click here to search skills!"
							class="flex-grow text-blue-500 print:hidden px-2 rounded-lg h-[30px] placeholder:text-[11px] text-[12px] py-0"
							bind:value={otherSearch}
						/>
						<span class="hidden print:inline text-slate-600 text-sm"
							><a href="https://www.andr3h3nriqu3s.com/cv?id={id}"
								>Click here to search other skills!</a
							></span
						>
					{/if}
				</h2>
			</div>
			<div class="p-3 bg-white w-[190mm] rounded-lg">
				<div class="flex flex-wrap gap-2 py-2 print:py-0">
					{#if otherSearch === ''}
						{#each application.flairs as flair}
							{@const hasDesc = flair.description && flair.showFullDescription === 1}
							<div class="min-w-0 {hasDesc ? 'flex-grow w-full' : ''}">
								{#if hasDesc}
									<div
										class="p-2 rounded-lg forced-color-adjust-none relative print:py-0"
										style="background: {flair.color};"
									>
										<Pill
											text-size="text-base print:text-sm"
											class="print:inline-block text-2xl py-0 mb-2"
											color={flair.color}
										>
											{flair.name}
										</Pill>
										<span class="hidden print:inline">:</span>
										<div class="bg-white my-1 print:inline p-1 rounded-md">
											{flair.description}
										</div>
									</div>
								{:else}
									<Pill text-size="text-base print:text-sm" color={flair.color}>
										{flair.name}
									</Pill>
								{/if}
							</div>
						{/each}
					{:else}
						{@const filtered_list = flairs.filter((a) =>
							a.name.match(new RegExp(otherSearch, 'i'))
						)}
						{#if filtered_list.length == 0}
							<div class="w-full text-center text-blue-500 font-bold text-2xl py-10">
								Could not find the skill you are looking for.
							</div>
						{:else}
							{#each filtered_list as flair}
								<div class="min-w-0 {flair.description ? 'flex-grow w-full' : ''}">
									{#if flair.description}
										<div
											class="p-2 rounded-lg forced-color-adjust-none"
											style="background: {flair.color};"
										>
											<div
												class="rounded-lg print:p-2 print:inline-block"
												style="background: {flair.color}; print-color-adjust: exact !important;"
											>
												{flair.name}
											</div>
											<span class="hidden print:inline">:</span>
											<div class="bg-white my-1 print:inline p-1 rounded-md">
												{flair.description}
											</div>
										</div>
									{:else}
										<div
											class="p-2 rounded-lg forced-color-adjust-none"
											style="background: {flair.color}; print-color-adjust: exact !important;"
										>
											{flair.name}
										</div>
									{/if}
								</div>
							{/each}
						{/if}
					{/if}
				</div>
			</div>
		{/if}
	{/if}

	<div class="p-4 print:hidden"></div>

	<!--div class="p-5"></div>
		<div>TODO: Previous projetcs</div -->
	<!-- div class="p-5"></div>
		<div>TODO: Info form</div -->
</div>

<style>
	@media print {
		.autoPadding {
			height: var(--auto-size);
		}
	}
</style>
