
MessageFormDiv.addEventListener('submit', async function(event) {
  event.preventDefault();
  await sendMessages(currentGroupID, UserID, MessageValuedDiv.value)
  MessageValuedDiv.value = ""
});


const observer = new IntersectionObserver(async (entries) => {
    if (entries[0].isIntersecting) {
        await f_loadMessages(currentGroupID)
    }
});

observer.observe(marker);

async function f_createMessage(userId, message) {
  var userName = await getUserCache(userId)
  //alert(userName)
  document.getElementById(MessagesDiv).insertAdjacentHTML("beforeend", `<div class='Message'><br><b>${userName["Username"]}:</b><br>${message}<br><br></div>`)
}
async function f_login(newUsername,newPassword) {
const permission = await Notification.requestPermission();

    await login(newUsername,newPassword)
    await f_GroupButtons(UserID)
    loginDiv.style = "visibility: hidden;"
    await createSubscription()
}
async function f_GroupButtons(userID) {
    var UserGroups = await getUserGroups(userID)
    for (i in UserGroups){
        var groupInfo = await getGroupInfo(UserGroups[i])
        var icon = await getFile("Groups",UserGroups[i],groupInfo["Icon"])
        var iconSrc = URL.createObjectURL(icon);

        document.getElementById(GroupListingDiv).insertAdjacentHTML("beforeend", `
            <button onclick="f_LoadChat('${UserGroups[i]}')"><img src="${iconSrc}" style="width: 64px; height: 64px;"/>
            </button><br>
            `)
    }
}
async function f_CreateGroup() {
    document.getElementById("GC-Create-Name").value = ""
    document.getElementById("GC-Create-Icon").value = ""
    createGCDiv.style = "visibility: visible;"
}
async function f_ShowFriends() {
    document.getElementById("GC-Create-Name").value = ""
    document.getElementById("GC-Create-Icon").value = ""
    FriendsDiv.style = "visibility: visible;"
    //alert(await getFriends(UserID))
    f_loadFriends()
}

async function loadAddUsers() {
  document.getElementById("AddUser").style = "visibility: visible;"
  addUsersDiv.innerHTML = "";
  //alert(currentGroupID)
  var usersInGroup = await getGroupUsers(currentGroupID)
  //alert(usersInGroup)
  var friends = await getFriends(UserID)
  //alert("friends:" + friends)
  for (i in friends) {
    if (usersInGroup.includes(friends[i])){
      continue
    }
  getFriendRecordID(UserID, friends[i])
    var UserName = (await getUserCache(friends[i]))["Username"]
addUsersDiv.insertAdjacentHTML("beforeend", `${UserName}<button onclick="addToGC('${currentGroupID}', '${friends[i]}', 'Normal')">Add</button> <br>`)
  }
}

async function f_LoadChat(GroupID) {
    currentGroupID = GroupID
    //alert(GroupID)
    await f_loadGC(GroupID)
    document.getElementById(MessagesDiv).scrollTop = document.getElementById(MessagesDiv).scrollHeight;
      const container = document.getElementById("Messages");
  const oldHeight = container.scrollHeight;
  const oldScrollTop = container.scrollTop;
  const newHeight = container.scrollHeight;
  container.scrollTop = container.scrollHeight;
    await f_loadUsers()
    
}
async function f_loadUsers() {
  var GroupUsers = await getGroupUsers(currentGroupID)
  //alert("GU" + GroupUsers)
  for (i in GroupUsers){
    var userInfo = await getUserCache(GroupUsers[i])
    UsersDiv.insertAdjacentHTML("beforeend", `${userInfo["name"]} (${userInfo["Username"]}) <br>`)}
}

async function f_loadMessages(GroupID) {
  const container = document.getElementById("Messages");

  const oldHeight = container.scrollHeight;
  const oldScrollTop = container.scrollTop;
    var Messages = (await getMessages(GroupID, currentLatestMessageTime))
    //alert(Messages)
    for (i in Messages){
    await f_createMessage((Messages[i])["Creator"], (Messages[i])["Message"])
    }
    const newHeight = container.scrollHeight;
    container.scrollTop = oldScrollTop + (newHeight - oldHeight);
}

async function f_loadGC(GroupChat) {
document.querySelectorAll('.Message').forEach(el => el.remove());
    currentLatestMessageTime = new Date().toISOString();
  await f_loadMessages(GroupChat)
}
async function f_loadFriends() {
  pendingFriendsDiv.innerHTML = "";
  var pendingFriends =  await getPendingFriendRequests(UserID)
  for (i in pendingFriends){
  var UserName = (await getUserCache(pendingFriends[i]))["Username"]
pendingFriendsDiv.insertAdjacentHTML("beforeend", `${UserName} <button onclick="acceptFriend('${UserID}', '${pendingFriends[i]}')">Accept</button> <button onclick="removeFriend('${UserID}', '${pendingFriends[i]}')">Deny</button>`)
  }
  currentFriendsDiv.innerHTML = "";
  var currentFriends =  await getFriends(UserID)
  for (i in currentFriends){
  getFriendRecordID(UserID, currentFriends[i])
    var UserName = (await getUserCache(currentFriends[i]))["Username"]
currentFriendsDiv.insertAdjacentHTML("beforeend", `${UserName}<button onclick="removeFriend('${UserID}', '${currentFriends[i]}')">Remove</button> <br>`)
  }
}
