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 { getMyAccount, unhideElementById } from './generalUseHelpers.js';
var isAscending = false;
function toggleListSortOrder(org_id) {
    isAscending = !isAscending;
    loadEvents(org_id);
}
function getEvents(titleOrDescription) {
    return __awaiter(this, void 0, void 0, function* () {
        var res;
        if (titleOrDescription == null) {
            res = yield fetch("/api/events" + (isAscending ? "?sort=asc" : ""));
            if (!res.ok)
                throw new Error("Błąd pobierania wydarzeń");
        }
        else {
            const payload = {
                titleOrDescription
            };
            res = yield fetch('/api/events/search', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            if (!res.ok)
                throw new Error("Błąd wyszukiwania wydarzeń");
        }
        const events = yield res.json();
        return events;
    });
}
function loadEvents(org_id, evs) {
    return __awaiter(this, void 0, void 0, function* () {
        const container = document.getElementById("eventList");
        if (!container)
            return;
        var events;
        try {
            if (evs == null) {
                events = yield getEvents();
            }
            else {
                events = yield evs;
            }
            if (events.length === 0) {
                container.innerHTML = "<p class='text-muted'>Brak wydarzeń do wyświetlenia.</p>";
                return;
            }
            // Wyczyść kontener przed dodaniem nowych
            container.innerHTML = '';
            for (const ev of events) {
                const card = document.createElement("div");
                card.className = "event-card filled";
                //card.innerHTML = `
                //    <span>${ev.title}</span>`
                // Do odkomentowania kiedy widok podglądu wydarzeń będzie gotowy
                card.innerHTML = `
                <span>
                    <a href="/view.html?event=${ev.eventId}" style="color: #2898BD">${ev.title}</a>
                    <p style="margin: 0">${ev.organisation}</p>
                </span>`;
                if (org_id == ev.organisationId) {
                    card.innerHTML += `
                <div>
                    <button class="edit-btn mod-btn" data-id="${ev.eventId}" id="edit-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#FFFFFF"><path d="M200-200h57l391-391-57-57-391 391v57Zm-80 80v-170l528-527q12-11 26.5-17t30.5-6q16 0 31 6t26 18l55 56q12 11 17.5 26t5.5 30q0 16-5.5 30.5T817-647L290-120H120Zm640-584-56-56 56 56Zm-141 85-28-29 57 57-29-28Z"/></svg>
                    </button>
                    <button class="remove-btn mod-btn" data-id="${ev.eventId}" id="remove-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" height="30px" viewBox="0 -960 960 960" width="30px" fill="#FFFFFF"><path d="M280-440h400v-80H280v80ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>
                    </button>
                </div>`;
                }
                container.appendChild(card);
            }
        }
        catch (err) {
            container.innerHTML = `<p class="text-danger">Błąd ładowania danych.</p>`;
            console.error(err);
        }
    });
}
document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, void 0, function* () {
    var org_id = -1;
    try {
        var user = yield getMyAccount();
        if (user) {
            if (user.isOrganisation) {
                unhideElementById(document, "mainContainer");
                unhideElementById(document, "addnewevent-btn");
                org_id = user.organisationId;
            }
            unhideElementById(document, "logout-btn");
        }
    }
    catch (_a) {
        // console.log("User not signed in. Failing gracefully.");
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }
    loadEvents(org_id);
    // listen for clicks
    const listSortToggleButton = document.getElementById("list-sort-btn");
    if (listSortToggleButton) {
        listSortToggleButton.addEventListener("click", () => toggleListSortOrder(org_id));
    }
    // and for enter in search bar
    const searchBar = document.getElementById('searchbar');
    searchBar.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            // console.log('Enter key pressed!');
            var searchResults = getEvents(searchBar.value);
            loadEvents(org_id, searchResults);
        }
    });
}));
