<template>
	<div class="bg-body-tertiary rounded p-3 shadow-sm">
		<LoadingComponent v-if="isLoading"/>

		<div v-else>
			<ActivitySummaryComponent v-if="activity" :activity="activity" :source="'activity'" @activityEditedFields="updateActivityFieldsOnEdit" :units="units" />
		</div>

		<!-- map zone -->
		<div class="mt-3 mb-3" v-if="isLoading">
			<LoadingComponent />
		</div>
		<div class="mt-3 mb-3" v-else-if="activity">
			<ActivityMapComponent :activity="activity" :source="'activity'"/>
		</div>
		
		<!-- gear zone -->
		<hr class="mb-2 mt-2" v-if="activity && authStore.isAuthenticated">
		<div class="mt-3 mb-3" v-if="isLoading && authStore.isAuthenticated">
			<LoadingComponent />
		</div>
		<div class="d-flex justify-content-between align-items-center" v-else-if="activity && authStore.isAuthenticated">
			<p class="pt-2">
				<span class="fw-lighter">
					{{ $t("activityView.labelGear") }}
				</span>
				<br>
				<span v-if="activity.activity_type === 1 || activity.activity_type === 2 || activity.activity_type === 3">
					<font-awesome-icon :icon="['fas', 'person-running']" />
				</span>
				<span v-else-if="activity.activity_type === 4 || activity.activity_type === 5 || activity.activity_type === 6 || activity.activity_type === 7 || activity.activity_type === 27">
					<font-awesome-icon :icon="['fas', 'fa-person-biking']" />
				</span>
				<span v-else-if="activity.activity_type === 8 || activity.activity_type === 9">
					<font-awesome-icon :icon="['fas', 'fa-person-swimming']" />
				</span>
				<span v-else-if="activity.activity_type === 21 || activity.activity_type === 22 || activity.activity_type === 23 || activity.activity_type === 24 || activity.activity_type === 25 || activity.activity_type === 26">
					<font-awesome-icon :icon="['fas', 'fa-table-tennis-paddle-ball']" />
				</span>
				<span class="ms-2" v-if="activity.gear_id && gear">{{ gear.nickname }}</span>
				<span class="ms-2" v-else>{{ $t("activityView.labelGearNotSet") }}</span>
			</p>
			<div class="justify-content-end">
				<!-- add gear button -->
				<a class="btn btn-link btn-lg link-body-emphasis" href="#" role="button" data-bs-toggle="modal" data-bs-target="#addGearToActivityModal" v-if="!activity.gear_id && activity.user_id === authStore.user.id">
					<font-awesome-icon :icon="['fas', 'fa-plus']" />
				</a>

				<!-- add gear to activity modal -->
				<AddGearToActivityModalComponent :activity="activity" :gearsByType="gearsByType" :gear="gearId" @gearId="updateGearIdOnAddGearToActivity"/>

				<!-- edit gear button -->
				<a class="btn btn-link btn-lg link-body-emphasis" href="#" role="button" data-bs-toggle="modal" data-bs-target="#addGearToActivityModal" v-if="activity.gear_id && activity.user_id === authStore.user.id">
					<font-awesome-icon :icon="['far', 'fa-pen-to-square']" />
				</a>

				<!-- Delete zone -->
				<a class="btn btn-link btn-lg link-body-emphasis" href="#" role="button" data-bs-toggle="modal" data-bs-target="#deleteGearActivityModal" v-if="activity.gear_id && activity.user_id === authStore.user.id">
					<font-awesome-icon :icon="['fas', 'fa-trash']" />
				</a>

				<!-- Modal delete gear -->
				<ModalComponent modalId="deleteGearActivityModal" :title="t('activityView.modalLabelDeleteGear')" :body="`${t('activityView.modalLabelDeleteGearBody')}`" actionButtonType="danger" :actionButtonText="t('activityView.modalLabelDeleteGearButton')" @submitAction="submitDeleteGearFromActivity"/>
			</div>
		</div>

		<!-- graphs -->
		<hr class="mb-2 mt-2">

		<!-- graphs and laps medium and above screens -->
		<div class="d-none d-sm-block" v-if="isLoading">
			<LoadingComponent />
		</div>
		<div class="d-none d-sm-block" v-else>
			<ActivityMandAbovePillsComponent :activity="activity" :activityActivityLaps="activityActivityLaps" :activityActivityWorkoutSteps="activityActivityWorkoutSteps" :activityActivityStreams="activityActivityStreams" :units="units" :activityActivityExerciseTitles="activityActivityExerciseTitles" :activityActivitySets="activityActivitySets" />
		</div>

		<!-- graphs and laps screens bellow medium -->
		<div class="d-lg-none d-block" v-if="isLoading">
			<LoadingComponent />
		</div>
		<div class="d-lg-none d-block" v-else>
			<ActivityBellowMPillsComponent :activity="activity" :activityActivityLaps="activityActivityLaps" :activityActivityWorkoutSteps="activityActivityWorkoutSteps" :activityActivityStreams="activityActivityStreams" :units="units" :activityActivityExerciseTitles="activityActivityExerciseTitles" :activityActivitySets="activityActivitySets" />
		</div>

		<!-- back button -->
		<BackButtonComponent />
	</div>
</template>

<script>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
// Importing the stores
import { useAuthStore } from "@/stores/authStore";
import { useServerSettingsStore } from "@/stores/serverSettingsStore";
// Import Notivue push
import { push } from "notivue";
// Importing the components
import ActivitySummaryComponent from "@/components/Activities/ActivitySummaryComponent.vue";
import ActivityMapComponent from "@/components/Activities/ActivityMapComponent.vue";
import ActivityMandAbovePillsComponent from "@/components/Activities/ActivityMandAbovePillsComponent.vue";
import ActivityBellowMPillsComponent from "@/components/Activities/ActivityBellowMPillsComponent.vue";
import LoadingComponent from "@/components/GeneralComponents/LoadingComponent.vue";
import BackButtonComponent from "@/components/GeneralComponents/BackButtonComponent.vue";
import ModalComponent from "@/components/Modals/ModalComponent.vue";
import AddGearToActivityModalComponent from "@/components/Activities/Modals/AddGearToActivityModalComponent.vue";
// Importing the services
import { gears } from "@/services/gearsService";
import { activities } from "@/services/activitiesService";
import { activityStreams } from "@/services/activityStreams";
import { activityLaps } from "@/services/activityLapsService";
import { activityWorkoutSteps } from "@/services/activityWorkoutStepsService";
import { activityExerciseTitles } from "@/services/activityExerciseTitlesService";
import { activitySets } from "@/services/activitySetsService";

export default {
	components: {
		ActivitySummaryComponent,
		ActivityMapComponent,
		ActivityMandAbovePillsComponent,
		ActivityBellowMPillsComponent,
		LoadingComponent,
		BackButtonComponent,
		ModalComponent,
		AddGearToActivityModalComponent,
	},
	setup() {
		const { t } = useI18n();
		const authStore = useAuthStore();
		const serverSettingsStore = useServerSettingsStore();
		const route = useRoute();
		const router = useRouter();
		const isLoading = ref(true);
		const activity = ref(null);
		const gear = ref(null);
		const gearsByType = ref([]);
		const gearId = ref(null);
		const activityActivityStreams = ref([]);
		const activityActivityLaps = ref([]);
		const activityActivityWorkoutSteps = ref([]);
		const units = ref(1);
		const activityActivityExerciseTitles = ref([]);
		const activityActivitySets = ref([]);

		async function submitDeleteGearFromActivity() {
			try {
				// Delete the gear from the activity
				const auxActivity = activity.value;
				auxActivity.gear_id = null;
				await activities.editActivity(auxActivity);

				// Show the success message
				push.success(t("activityView.successMessageGearDeleted"));

				// Update the activity gear
				activity.value.gear_id = null;
			} catch (error) {
				push.error(`${t("activityView.errorMessageDeleteGear")} - ${error}`);
			}
		}

		async function updateGearIdOnAddGearToActivity(gearId) {
			// Update the activity gear
			gear.value = await gears.getGearById(gearId);
			activity.value.gear_id = gearId;

			// Show the success message
			push.success(t("activityView.successMessageGearAdded"));
		}

		function updateActivityFieldsOnEdit(data) {
			// Update the activity fields
			activity.value.name = data.name;
			activity.value.description = data.description;
			activity.value.activity_type = data.activity_type;
			activity.value.visibility = data.visibility;
		}

		onMounted(async () => {
			try {
				// Get the activity by id
				if (authStore.isAuthenticated) {
					activity.value = await activities.getActivityById(route.params.id);
				} else {
					if (serverSettingsStore.serverSettings.public_shareable_links) {
						activity.value = await activities.getPublicActivityById(
							route.params.id,
						);
						if (!activity.value) {
							return router.push({
								path: "/login",
								query: { errorPublicActivityNotFound: "true" },
							});
						}
					} else {
						return router.push({
							path: "/login",
							query: { errorpublic_shareable_links: "true" },
						});
					}
				}

				// Check if the activity exists
				if (!activity.value) {
					return router.push({
						path: "/",
						query: { activityFound: "false", id: route.params.id },
					});
				}

				if (authStore.isAuthenticated) {
					// Set the units
                    units.value = authStore.user.units;

					// Get the activity streams by activity id
					activityActivityStreams.value =
						await activityStreams.getActivitySteamsByActivityId(
							route.params.id,
						);

					// Get the activity laps by activity id
					activityActivityLaps.value = await activityLaps.getActivityLapsByActivityId(
						route.params.id,
					);

					// Get the activity workout steps by activity id
					activityActivityWorkoutSteps.value =
						await activityWorkoutSteps.getActivityWorkoutStepsByActivityId(
							route.params.id,
						);

					// Get the activity exercise titles
					activityActivityExerciseTitles.value =
						await activityExerciseTitles.getActivityExerciseTitlesAll();

					// Get the activity sets by activity id
					activityActivitySets.value = await activitySets.getActivitySetsByActivityId(
						route.params.id,
					);
				} else {
					// Set the units
					units.value = serverSettingsStore.serverSettings.units;

					// Get the activity streams by activity id
					activityActivityStreams.value =
						await activityStreams.getPublicActivityStreamsByActivityId(
							route.params.id,
						);

					// Get the activity laps by activity id
					activityActivityLaps.value = await activityLaps.getPublicActivityLapsByActivityId(
						route.params.id,
					);

					// Get the activity workout steps by activity id
					activityActivityWorkoutSteps.value =
						await activityWorkoutSteps.getPublicActivityWorkoutStepsByActivityId(
							route.params.id,
						);

					// Get the activity exercise titles
					activityActivityExerciseTitles.value =
						await activityExerciseTitles.getPublicActivityExerciseTitlesAll();

					// Get the activity sets by activity id
					activityActivitySets.value = await activitySets.getPublicActivitySetsByActivityId(
						route.params.id,
					);
				}

				if (authStore.isAuthenticated) {
					if (activity.value.gear_id) {
						gear.value = await gears.getGearById(activity.value.gear_id);
						gearId.value = activity.value.gear_id;
					}

					if (
						activity.value.activity_type === 1 ||
						activity.value.activity_type === 2 ||
						activity.value.activity_type === 3 ||
						activity.value.activity_type === 11 ||
						activity.value.activity_type === 12
					) {
						gearsByType.value = await gears.getGearFromType(2);
					} else {
						if (
							activity.value.activity_type === 4 ||
							activity.value.activity_type === 5 ||
							activity.value.activity_type === 6 ||
							activity.value.activity_type === 7
						) {
							gearsByType.value = await gears.getGearFromType(1);
						} else {
							if (
								activity.value.activity_type === 8 ||
								activity.value.activity_type === 9
							) {
								gearsByType.value = await gears.getGearFromType(3);
							} else {
								if (
									activity.value.activity_type === 21 ||
									activity.value.activity_type === 22 ||
									activity.value.activity_type === 23 ||
									activity.value.activity_type === 24 ||
									activity.value.activity_type === 25 ||
									activity.value.activity_type === 26
								) {
									gearsByType.value = await gears.getGearFromType(4);
								}
							}
						}
					}
				}
			} catch (error) {
				if (error.toString().includes("422")) {
					router.push({
						path: "/",
						query: { activityFound: "false", id: route.params.id },
					});
				}
				// If there is an error, set the error message and show the error alert.
				push.error(
					`${t("activityView.errorMessageActivityNotFound")} - ${error}`,
				);
			}

			isLoading.value = false;
		});

		return {
			t,
			authStore,
			isLoading,
			activity,
			units,
			gear,
			gearId,
			activityActivityStreams,
			gearsByType,
			submitDeleteGearFromActivity,
			updateGearIdOnAddGearToActivity,
			updateActivityFieldsOnEdit,
			activityActivityLaps,
			activityActivityWorkoutSteps,
			activityActivityExerciseTitles,
			activityActivitySets,
		};
	},
};
</script>