var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { getEvent, getMyAccount, unhideElementById, getMyRegisteredEventIds } from './generalUseHelpers.js';
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const eventId = urlParams.get('event');
document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, void 0, function* () {
    var container = document.getElementById("mainContainer");
    const modifyBtn = document.getElementById("editBtn");
    const removeBtn = document.getElementById("removeBtn");
    const applyBtn = document.getElementById("applyBtn");
    var org_id = -1;
    try {
        var user = yield getMyAccount();
        if (user) {
            if (user.isOrganisation) {
                org_id = user.organisationId;
            }
            unhideElementById(document, "logout-btn");
        }
    }
    catch (_a) {
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }
    var thisEvent = null;
    try {
        if (eventId)
            thisEvent = yield getEvent(eventId);
    }
    catch (err) {
        if (container !== null)
            container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powrót -></a></p>`;
    }
    if (thisEvent == null) {
        if (container !== null)
            container.innerHTML = `<p class="text-danger">Błąd we wczytywaniu wydarzenia. <a href="/" style="color:#2898BD;">Powrót -></a></p>`;
    }
    else {
        const titleText = document.getElementById("titleText");
        const locationText = document.getElementById("locationText");
        const descText = document.getElementById("descText");
        const dateText = document.getElementById("dateText");
        const organizerText = document.getElementById("organizerText");
        const newdateText = new Date(thisEvent.eventDate).toLocaleDateString('pl-PL');
        const newtimeText = new Date(thisEvent.eventDate).toLocaleTimeString('pl-PL');
        titleText.innerHTML = thisEvent.title + ` (#${eventId})`;
        locationText.innerHTML = "Place: " + thisEvent.location;
        descText.innerHTML = thisEvent.description;
        dateText.innerHTML = "When: " + newdateText + " " + newtimeText; //thisEvent.eventDate;
        organizerText.innerHTML = "Organized by: " + thisEvent.organisationName;
        if (org_id == thisEvent.organisationId) {
            // Użytkownik jest organizacją, która
            // stworzyła to wydarzenie
            unhideElementById(document, "editBtn");
            unhideElementById(document, "removeBtn");
        }
        else if (org_id == -1) {
            // Użytkownik jest wolontariuszem
            const registeredIds = yield getMyRegisteredEventIds();
            const isRegistered = registeredIds.includes(Number(eventId));
            if (isRegistered) {
                unhideElementById(document, "leaveBtn");
            }
            else {
                unhideElementById(document, "applyBtn");
            }
        }
        unhideElementById(document, "mainContainer");
    }
    if (modifyBtn) {
        modifyBtn.addEventListener("click", (e) => {
            window.location.href = "/modify.html?event=" + eventId;
        });
    }
    if (removeBtn) {
        removeBtn.addEventListener("click", (e) => __awaiter(void 0, void 0, void 0, function* () {
            const confirmed = confirm("Really delete?");
            if (!confirmed)
                return;
            try {
                // Wysyła żądanie DELETE do API
                const response = yield fetch(`/api/events/${eventId}`, {
                    method: "DELETE"
                });
                if (response.ok) {
                    alert("Event deleted.");
                    window.location.href = "/";
                }
                else {
                    alert("Couldn't delete event.");
                }
            }
            catch (err) {
                alert("Couldn't connect.");
                console.error(err);
            }
        }));
    }
    if (applyBtn) {
        applyBtn.addEventListener("click", (e) => __awaiter(void 0, void 0, void 0, function* () {
            var _b;
            try {
                const response = yield fetch(`/api/events/join/${eventId}`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                });
                const result = yield response.json();
                if (result.success) {
                    applyBtn.disabled = true;
                    applyBtn.textContent = "Applied Succesfully";
                }
                else {
                    alert(`Error: ${(_b = result.error_msg) !== null && _b !== void 0 ? _b : "Unknown error occurred."}`);
                }
            }
            catch (error) {
                console.error("Failed to apply:", error);
                alert("Failed to apply due to a network or server error.");
            }
        }));
    }
}));
