Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
homePage.ts 13.04 KiB
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./Database/database.js";
import { logout } from "./Database/authentication.js";
import { getUsers, getSuggestions, getImprovementWorks, getUnits, getObjectById, getImprovementWorksForUser } from "../client/Database/database.js";

function logoutUser(event : Event) {
    event.preventDefault();
    alert('logout')
    
    logout()
}

/* onAuthStateChanged(auth, (user) => {
    const userNameLink = document.getElementById('userNameLink') as HTMLAnchorElement;
    const logOutLink = document.getElementById('logOutLink');

    if ( userNameLink && logOutLink){
        if ( user ) {
            var x = user;
            // User is logged in, 'user' contains user information
            console.log("User is logged in:", user.uid, user.email, user);
            console.log(user.uid)
            $("#user-name").text("Nytt namn");
            userNameLink.textContent = user.email;
            userNameLink.href = 'homePage.html';
            logOutLink.style.display = 'inline'; // Show Logga ut
            logOutLink.addEventListener('click', logoutUser);
            
        } else {
            // No user is logged in
        }
    }
});
 */

interface Project {
    ID: string;
    name: string;
    current_stage: string;
    content: string;
    unit_ID: string;
    date_started: Date;
}

let myIdeaCards: { [key: number]: IdeaCard } = {};

class IdeaCard {
  private header: string;
  private department: string;
  private name: string;
  private description: string;
  private upvoteCount: number;
  private id: number;

  constructor(
    id: number,
    header: string,
    department: string,
    name: string,
    description: string,
    upvoteCount: number
  ) {
    this.header = header;
    this.department = department;
    this.name = name;
    this.description = description;
    this.upvoteCount = upvoteCount;
    this.id = id;
  }
  generateHTML(): string {
    return `<div class="totalExpandedIdeaCard">
          <div class="ideaCard">
              <div class="ideaCardBorder">
                  <div class="ideaCardImage">
                      <img src="../images/pinkFaded.png" class ="pinkFaded" alt="pinkFaded">
                  </div>
                  <div class="ideaCardMiddleText">
                      <p id="ideaCardHeader" class="ideaCardFont">${this.header}</p>
                      <p id="ideaCardDepartment" class="ideaCardFont">${this.department}</p>
                      <p id="ideaCardName" class="ideaCardFont">${this.name}</p>
                      <p id="ideaCardMoreInfo${this.id}" class="ideaCardFont moreInfoClass"> > Mer information</p>
                  </div>
              </div>
              <div class="ideaCardUpvotes">
                  <img src="images/upvoteIcon.png" class ="upvoteIcon" alt="upvoteIcon">
                  <p id ="upvoteNumber" class="ideaCardFont">${this.upvoteCount}</p>
              </div>
          </div>
          <div id="expandedContent${this.id}" class= "expandedIdeaContent" style ="display : none;">
              <div class="expandedDescriptionText">
                  <p class="ideaCardFont" id="expandedHeader">Om ideen</p>
                  <p id="expandedDescription">${this.description}</p>
              </div>
              <div class="expandedCommentAndButton id = "expandedCommentAndButton${this.id}">
                  <div class="expandedComment">
                      <p class="ideaCardFont">Kommentarer</p>
                      <p class="ideaCardFont">Komment 1</p>
                      <p class="ideaCardFont">K0mment 2</p>
                  </div>
                  <div class="expandedButton">
                      <button class="initiateProject" onclick="myIdeaCards[${this.id}].loadInitiatePage()">Initiera Project</button>
                  </div>
              </div>
          </div>
      </div>`;
  }



  showMoreInfo(blockId: string, thisTextId: string): void {
    const blockElement = document.getElementById(blockId);
    if (blockElement) {
      blockElement.style.display = "flex";
    }

    const textElement = document.getElementById(thisTextId);
    if (textElement) {
      textElement.innerText = "^ Stäng detaljer";
    }
  }

  closeMoreInfo(blockId: string, thisTextId: string): void {
    const blockElement = document.getElementById(blockId) as HTMLSelectElement;
    if (blockElement) {
      blockElement.style.display = "none";
    }
    const textElement = document.getElementById(thisTextId);
    if (textElement) {
      textElement.innerText = "> Mer information";
    }
  }

  loadInitiatePage() {
    alert("The initiate project page should now be loaded");
  }
}
async function createNewCards(className: string, container: Element, signedInUserHsaID: string) {
  let user = await getObjectById("users",signedInUserHsaID);
  let userSuggestions = await getSuggestions({creatorHsaId: user.id})
  //If there exist filter use those instead to get matching suggestions rest should not need to be changed
  var counter = 0;
  userSuggestions.forEach(async (suggestion) => {
    var unit = await getObjectById("unit", suggestion.unitId);
    var user = await getObjectById("users", suggestion.creatorHsaId);
    createNewIdeaCard(
      suggestion.name,
      unit.name,
      user.firstName + " " + user.lastName,
      suggestion.content,
      suggestion.upvotes.length,
      className,
      container,
      counter
    );
    counter = counter + 1;
  });
}
async function createNewIdeaCard(
    header: string,
    department: string,
    name: string,
    description: string,
    upvoteCount: number,
    className: string,
    container: Element,
    ID: number
  ) {
    let card = new IdeaCard(
      ID,
      header,
      department,
      name,
      description,
      upvoteCount
    );
    let cardHTML = card.generateHTML();
    myIdeaCards[ID] = card;
    let div = document.createElement("div");
    div.className = className; // Set the class name(s) here
    div.innerHTML = cardHTML;
    container.appendChild(div);
  }
  
 export async function loadPage() {
     const container = document.querySelector('#container-fluid');


     if (!container) return; // Stop if the container isn't found
     fetch('homePage.html')
             .then(response => response.text())
             .then(async data => { 
                 // Create a temporary container element to hold the loaded content
                 const tempContainer = document.createElement('div');
                 tempContainer.innerHTML = data;

                 // Select the specific element with the class you want
                 const specificElement = tempContainer.querySelector('.main-content');

                 if (specificElement) {
                     // Insert the specific element into the target element
                     container.insertBefore(specificElement, container.firstChild);
                 }

                 var tmp = localStorage.getItem('user')
                 console.log(tmp)
                 if (!tmp){
                    console.log("there is not an user in localStorage")
                    return;
                 }
                 var user = JSON.parse(tmp)[0];
                 
                 const suggestionContainer = document.getElementById("suggestion-container");
                 if(suggestionContainer) {
                   await createNewCards("HomePageIdeaCardDiv",suggestionContainer, user.id);
                   
                 }

                 console.log(user.firstName + "user.firstname")
                 const nameHeaderElement = document.getElementById('user-name-header')
                 const nameElement = document.getElementById('user-name');
                 const emailElement = document.getElementById('user-email');
                 const roleElement = document.getElementById('user-role');
                 const unitElement = document.getElementById("user-unit");
                 
                 let userFullName = user.firstName + " " + user.lastName;
                 let userUnits = await getUnits({unitId: user.unitId});
                 let userUnit = userUnits[0];
            
                 if (emailElement && roleElement && nameElement && unitElement && nameHeaderElement) {
                     nameHeaderElement.textContent = userFullName
                     nameElement.textContent = userFullName;
                     unitElement.textContent = userUnit.name;
                     emailElement.textContent = user.email;
                     roleElement.textContent = "undefined";
                     
                 }
                 const projectContainer = document.getElementById("project-container");
                 if(projectContainer) {
                  await getProjects(projectContainer, user.id);
                 }
                
             })
             .catch(error => {
                 console.error('Failed to load the external HTML file:', error);
             });
            }
     



            async function getProjects (selectElement : HTMLElement, /*listenersLoaded:boolean,*/ userHsaId: string) {
              const data = await getImprovementWorksForUser(userHsaId);
              let id = 0;
              data.forEach(async(project) => {
                  let title = project.name;
                  let department = await getObjectById('unit', project.unitId);
                  if(department) {
                      let name = "Projektledare"; //Waiting for backend fix
                      let description = project.content;
                      let i = id;
                      let card = new projectCard(i, name, department.name, title, description, project.id);
                      projectCards[i] = card;
                      let cardHTML = card.generateHTML();
                      //addEventListener(listenersLoaded, project.id, card);
                      let div = document.createElement('div');
                      div.className = 'homePageProjectCardDiv'; // Set the class name(s) here
                      div.innerHTML = cardHTML;
                      if (!selectElement) return; 
                      selectElement.appendChild(div); // Stop if the container isn't found
                      id ++;   
                  } else {
                      console.log(project.unitId + " is not a unit"); //Unit Ids on improvement work that do not exist 
                  }
              });
          }



    let projectCards: { [key: number]: projectCard } = {};

class projectCard {
    private name: string; // Projectowner
    private department: string;
    private title: string;
    private description: string;
    private id: number;
    private projectId: string;

    constructor(id: number, name: string, department: string, title: string, description: string, projectId: string) {
      this.name = name;
      this.department = department;
      this.title = title;
      this.description = description;
      this.id = id;
      this.projectId = projectId;
    }

    showMoreInfo(blockId: string, thisTextId: string): void {
        const blockElement = document.getElementById(blockId);
        if (blockElement) {
            blockElement.style.display = "flex";
        }

        const textElement = document.getElementById(thisTextId);
        if (textElement) {
            textElement.innerText = '^ Stäng detaljer';
        }
    }

    closeMoreInfo(blockId: string, thisTextId: string): void {
        const blockElement = document.getElementById(blockId) as HTMLSelectElement;
        if (blockElement) {
            blockElement.style.display = "none";
        }
        const textElement = document.getElementById(thisTextId);
        if (textElement) {
            textElement.innerText = '> Mer information';
        }
    }
    
    loadInitiatePage() {
        alert('The initiate project page should now be loaded');
    }

    

    generateHTML(): string {
        return `<div class="homeTotalExpandedOngoingWorkCard">
        <div style="cursor: pointer;" class="flex-container ongoingCard" id="${this.projectId}">
            <div class="ongoingCardImageContainer toSinglePage">
                <div class = "flex-box ongoingCardImage toSinglePage" id="pinkFaded"></div>
            </div>
            <div class="div ongoingCardInfo toSinglePage">
                <p class="toSinglePage" id="ongoingCardManager">${this.name}</p>
                <p class="toSinglePage" id="ongoingCardDepartment">${this.department}</p>
                <p class="toSinglePage" id="ongoingCardIdeaTitle">${this.title}</p>
            </div>

            <!--<button data-project-id="${this.id}" class="projectButton" role="button">Gå till projektsidan</button>-->


            <div class="container ongoingSeeCardDetails toSinglePage">
                <div class="ongoingSeeCardDetailsInner">
                    <p id="ongoingSeeDetailsButton${this.projectId}" class = "moreInfoClass">> Mer information</p>
                </div>
            </div>
        </div> 
        <div class = "expandedOngoingWorkCard" id="expandedOngoingWorkCard${this.projectId}" style="display: none;">
            <div class ="expandedTextOngoingWorkCard">
            ${this.description}
            </div>
        </div>
        </div> `
      }
}