<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BIMserver Project Contributions</title>
    <style>
        /* Styles adapted from survey.html */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            justify-content: center;
            background-color: #f8f9fa;
            align-items: center;
            margin: 0;
            padding: 20px;
            flex-direction: column;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 800px;
            width: 100%;
        }
        .header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .logo {
            max-height: 60px;
        }
        h1 {
            margin-bottom: 20px;
            font-size: 22px;
            color: #333;
        }
        .box {
            display: inline-block;
            margin: 10px;
            padding: 20px;
            width: 150px;
            height: 120px;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            overflow: hidden;
        }
        .box:hover {
            background-color: #f1f1f1;
        }
        .box.selected {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        .info-text {
            margin-top: 10px;
            font-size: 14px;
            color: #333;
        }
    </style>
</head>
<body>
<div class="header">
    <img src="../static/images/logo1.png" alt="Logo 1" class="logo">
    <a href="https://3d.bk.tudelft.nl/"><img src="../static/images/logo2.png" alt="Logo 2" class="logo"></a>
</div>
<div style="color: red; text-align: center; margin-bottom: 20px; font-size: 16px;">
    Please allow the pop-up, authorize the connection to BIMserver.center , and close the pop-up window afterward.
</div>
<div class="container">
    <h1>Select a Project:</h1>
    <div id="projects"></div>

    <h1>Contributions for the Selected Project:</h1>
    <div id="contributions"></div>
</div>
<form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data" style="display: none;">
    <input type="file" name="file" id="file-input">
</form>
<script>
    const fileInput = document.getElementById('file-input');
    const form = document.getElementById('upload-form');
    async function getProjects() {
        const clientId = '473:6536781D-C8A0-4B55-998C-B5C9D588A177';
        const clientSecret = 'E1F0FE2E-009D-48A7-8042-443C2EE3C8F3';
        const scope = [
            "DATA_USER_READ",
            "PROJECTS_USER_READ",
            "PROJECTS_USER_WRITE",
            "CONTRIBUTIONS_USER_READ",
            "CONTRIBUTIONS_USER_WRITE"
        ];

        try {
            const loginResponse = await fetch('https://apis.bimserver.center/v1/BIMSERVER/LOGIN', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    client_id: clientId,
                    client_secret: clientSecret,
                    scope: scope
                })
            });

            const loginData = await loginResponse.json();
            if (loginData.status === "OK") {
                const authWindow = window.open(loginData.url, '_blank', 'width=600,height=400');
                await new Promise((resolve) => {
                    const interval = setInterval(() => {
                        if (authWindow.closed) {
                            clearInterval(interval);
                            resolve();
                        }
                    }, 1000);
                });

                const sessionTemp = loginData.session_temp;
                const security_id = loginData.security_id;
                const sessionResponse = await fetch(`https://apis.bimserver.center/v1/BIMSERVER/LOGIN/${sessionTemp}?security_id=${security_id}&lang_interface=en`, {
                    method: 'GET'    
                });
                const sessionData = await sessionResponse.json();

                if (sessionData.status === "OK") {
                    const sessionId = sessionData.session_id;

                    const projectsResponse = await fetch('https://apis.bimserver.center/v1/BIMSERVER/PROJECTS', {
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${sessionId}`
                        }
                    });

                    const projectsData = await projectsResponse.json();
                    if (projectsData.status === "OK") {
                        displayProjects(projectsData.records, sessionId);
                    } else {
                        console.error("Error fetching projects:", projectsData.error.message);
                    }
                } else {
                    console.error("Error fetching session token:", sessionData.error.message);
                }
            } else {
                console.error("Error logging in:", loginData.error.message);
            }
        } catch (error) {
            console.error("Request failed:", error);
        }
    }

    function displayProjects(projects, sessionId) {
        const projectsDiv = document.getElementById('projects');
        projectsDiv.innerHTML = ""; 

        projects.forEach(project => {
            const projectElement = document.createElement('div');
            projectElement.className = 'box';
            projectElement.innerHTML = `
                <div class="info-text"><strong>${project.name}</strong></div>
            `;
            projectElement.onclick = () => selectProject(projectElement, project.id, sessionId);
            projectsDiv.appendChild(projectElement);
        });
    }

    function selectProject(element, projectId, sessionId) {
        deselectAll('projects');
        element.classList.add('selected');
        getContributions(projectId, sessionId);
    }

    async function getContributions(projectId, sessionId) {
        const contributionsResponse = await fetch(`https://apis.bimserver.center/v1/BIMSERVER/CONTRIBUTIONS?project_id=${projectId}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${sessionId}`
            }
        });

        const contributionsData = await contributionsResponse.json();
        if (contributionsData.status === "OK") {
            displayContributions(contributionsData.records, sessionId);
        } else {
            console.error("Error fetching contributions:", contributionsData.error.message);
        }
    }

    function displayContributions(contributions, sessionId) {
        const contributionsDiv = document.getElementById('contributions');
        contributionsDiv.innerHTML = ""; 

        contributions.forEach(contribution => {
            const contributionElement = document.createElement('div');
            contributionElement.className = 'box';
            contributionElement.innerHTML = `
                <div class="info-text"><strong>${contribution.name}</strong></div>
                <p>ID: ${contribution.id}</p>
                <p>${contribution.description || 'No description available.'}</p>
            `;
            contributionElement.onclick = () => selectContribution(contributionElement, contribution.id, sessionId);
            contributionsDiv.appendChild(contributionElement);
        });
    }

    async function selectContribution(element, contributionId, sessionId) {
        deselectAll('contributions');
        element.classList.add('selected');
        // console.log("Selected Contribution ID:", contributionId);
        // alert(`Selected Contribution ID: ${contributionId}`);
        const contributionResponse = await fetch(`https://apis.bimserver.center/v1/BIMSERVER/contributions/${contributionId}?expand=owner&lang_interface=en`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${sessionId}`
            }
        });
        const contributionFile = await contributionResponse.json();
        const Docs = contributionFile.record.documents
        for (const Doc of Docs) {
            const docId = Doc.id;
            const docResponse = await fetch(`https://apis.bimserver.center/v1/BIMSERVER/documents/${docId}?expand=owner&lang_interface=en`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${sessionId}`
                }
            })
            const docFile = await docResponse.json();
            if (docFile.record.name.endsWith('.ifc')){
                const IFCfileurl = docFile.record.url
                downloadAndSubmitIFCFile(IFCfileurl , docFile.record.name);
                break;
            }
        }
    }
    async function downloadAndSubmitIFCFile(url,filename) {
        try {
            // Fetch the IFC file from the URL
            const response = await fetch(url);
            const blob = await response.blob();

            // Create a File object from the blob
            const ifcFile = new File([blob], filename, { type: blob.type });

            // Populate the form's file input with the IFC file
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(ifcFile);
            fileInput.files = dataTransfer.files;

            // Submit the form
            form.submit();
        } catch (error) {
            console.error('Failed to download and submit IFC file:', error);
            alert('Failed to submit IFC file');
        }
    }
    function deselectAll(section) {
        const parentDiv = document.getElementById(section);
        Array.from(parentDiv.getElementsByClassName('box')).forEach(box => box.classList.remove('selected'));
    }

    getProjects();

</script>

</body>
</html>