<script lang="ts" setup>
import RitzenbergenLib from "../ritzenbergenlib.ts";
import { defineProps, ref, watchEffect } from "vue";

const props = defineProps({
	form: {
		type: RitzenbergenLib.Formular,
		required: true,
	},
	token: {
		type: String,
		required: false,
		default: ""
	}
});

const form = ref(props.form);


const results = ref([]);
const myfields = ref([]);
watchEffect(() => {
	fetch(
		RitzenbergenLib.RitzenbergenLib.api(
			"/formulare/get_results.php?id=" + form.value.id
		)
	)
		.then((res) => res.json())
		.then((data) => {
			if(data.error){
				// Admin Rechte nötig
				fetch(RitzenbergenLib.RitzenbergenLib.api("/admin/formulare/ergebnisse.php?formular="+form.value.id),{
						headers: {
								"Authorization":props.token
						}
				})
				.then((res)=>res.json())
				.then((data)=>{
						results.value=data;
				})
			} else {
				results.value = data;
			}
		});

	myfields.value = [];
	form.value.fields.forEach((field: RitzenbergenLib.Field) => {
		if (myfields.value.find((el) => el.name == field.name) == undefined) {
			myfields.value.push(field);
		}
	});
});

function prettyResult(result: any) {
	if (result == undefined) {
		return "";
	}
	if (result.value instanceof Array) {
		let tempresult = result.value;
		let cancel = false;
		tempresult = tempresult.map((el) => {
			let field = form.value.fields.find((f) => f.value == el);
			if (field == undefined) {
				cancel = true;
				return el;
			}
			return field.displayvalue ?? el;
		});
		if (!cancel) result.value = tempresult;

		return result.value.join(", ");
	}
	if (result.type == "radio") {
		let field = form.value.fields.find((f) => f.value == result.value);
		if (field != undefined) {
			return field.displayvalue ?? result.value;
		}
	}
	return result.value;
}
</script>

<template>
		
	<h1>Ergebnisse {{ form.name }}</h1>
	<div class="main">
	<table>
		<thead>
			<tr>
				<td v-for="(field, i) in myfields" :key="i">
					{{ field.displayname ?? field.name }}
				</td>
				<td>Zeitstempel</td>
			</tr>
		</thead>
		<tbody>
			<tr v-for="(result, ri) in results" :key="ri">
				<td
					v-if="result.data != undefined"
					v-for="(field, fi) in myfields"
					:key="fi"
					:style="
						field.type == 'color'
							? {
									backgroundColor: result.data.find(
										(el) => el.name == field.name
									).value,
									width: '10px',
									height: '10px',
								}
							: {}
					"
				>
					<span v-if="field.type != 'color'">{{
						prettyResult(
							result.data.find(
								(el) =>
									el.name == field.name ||
									el.name + "[]" == field.name
							)
						)
					}}</span>
					<span v-else></span>
				</td>
				<td>{{ result.timestamp }}</td>
			</tr>
		</tbody>
	</table>
	</div>
</template>

<style scoped>
@import "../assets/css/bulitipp2.css";
td {
	min-width: 150px;
	min-height: 0;
}
tbody, table, .main{
		overflow-x: scroll;
}
thead tr td {
	background-color: #efefef;
}
h1 {
		text-align: center;
}
</style>
