<script lang="ts">

  import { onMount } from "svelte";
    import { binding_callbacks } from "svelte/internal";
  import Button from "../../pieces/Button.svelte";
  import DisplayAUser from "../../pieces/DisplayAUser.svelte";

  // Ok so i need to test all the paths Cherif has made but a major one doesn't work yet...
  // in the mean time, i need to make some other stuff look nice
  // what do i want?

/*
Ideas
- a list of all users and if they're active
could be a list of friends and if they're active but i can't see that yet
- I click on a thing and it lets me see all the users and i get a button that lets me add them
  - would that be like a serachable list of all users?
  - am i skipping optimization? i mean for now yes, but like



*/




  let errors = {friendRequest: '',};
  let set = {friendUsername: '', friendId: Number}

  let user;
  let allUsers;
  let myFriends;
  let requestsMade, requestsRecieved;
  let userBeingViewed;



  onMount( async() => {
    // yea no idea what
    // i mean do i fetch user? i will for now
    user = await fetch('http://transcendance:8080/api/v2/user')
      .then( (x) => x.json() );

    // userBeingViewed = user;
    // console.log('user is ')
    // console.log(user)
    // console.log(user.username)

    myFriends = await fetch("http://transcendance:8080/api/v2/network/myfriends")
      .then( (x) => x.json() );

    // console.log('my friends')
    // console.log(myFriends)

    requestsMade = await fetch('http://transcendance:8080/api/v2/network/pending')
      .then( x => x.json() );

    // console.log('Requests pending ');
    // console.log(requestsMade);


    requestsRecieved = await fetch('http://transcendance:8080/api/v2/network/received')
      .then( x => x.json() );

    // console.log('Requests received ');
    // console.log(requestsRecieved);

    allUsers = await fetch('http://transcendance:8080/api/v2/user/all')
      .then( x => x.json() );
    // console.log('got all users ' + allUsers)


  })


  const displayAllUsers = async() => {
    allUsers = await fetch('http://transcendance:8080/api/v2/user/all')
      .then( x => x.json() );
    // console.log('got all users ' + allUsers)
  };


  const displayAllFriends = async() => {
    myFriends = await fetch('http://transcendance:8080/api/v2/network/myfriends')
      .then( x => x.json() );
    // console.log('got all friends ' + allFriends)
  };

  const displayRequestsMade = async() => {
    requestsMade = await fetch('http://transcendance:8080/api/v2/network/pending')
      .then( x => x.json() );
    // console.log('got requests made ' + requestsMade)
  };

  let sentFriendRequest;
  const sendFriendRequest = async(potentialFriendUsername) => {
    set.friendUsername = '';
    errors.friendRequest = '';
    let valid = false;
    if (potentialFriendUsername === user.username) {
      errors.friendRequest = "You can't friend yourself."
      valid = false;
    } else {
      set.friendUsername = potentialFriendUsername;
      valid = true;
    }

    if (valid) {
      sentFriendRequest = await fetch("http://transcendance:8080/api/v2/network/myfriends", {
          method : "POST",
          headers: { 'Content-Type': 'application/json'},
            body: JSON.stringify({
            "receiverUsername": set.friendUsername,
            "status": "R"
          })
        })
        .then( x => x.json())
    }
  };

  // let sendUsername;
  const viewAUser = async(aUser) => {
    userBeingViewed = aUser;
    // sendUsername = userBeingViewed.username;

    // prolly like fetch if you're friends or not?
    // GET http://transcendance:8080/api/v2/networks/myfriends?username=aUser but i need to make that as long as Cherif
      // doesn't have a better option
      // like i want this thing to return the Friendship ID ideally
  };

  const blockAUser = async(friendshipId) => {

  };


</script>


<!-- svelte-ignore a11y-click-events-have-key-events -->
<div class="top-grid">

  <div class="all-users-sidebar">
    <h3>All Users</h3>
    {#if allUsers === undefined}
      <div class="error">Failed to load all users</div>
    {:else}
      <!-- problem, i can't use user.id since Cherif doesn't want to expost that to the front...
      is there something else i could use? -->
      <!-- add a thing so it doesn't display the current user just all the other users -->

      <!-- does this work? -->
      <!-- {#each allUsers as aUser (aUser.username)} -->
      {#each allUsers as aUser }
        <!-- <div class="a-user" on:click={() => displayAUser(aUser.username)}>{aUser.username}</div> -->
        <div class="a-user" on:click={() => viewAUser(aUser)}>{aUser.username}</div>
        <!-- i could make an indicator component? like green for connected or something?
        i could use words but color them?
        i could make it so if they're in a game  -->
        <div class="status a-user">{aUser.status}</div>
        <br>
      {/each}
    {/if}

  </div>


  <div class="main-display">

    <h1>Main Display</h1>

    <!-- use an #await here too? -->
    <!-- you can do better, like an on load sort of thing -->
    <!-- {#if userBeingViewed !== undefined && userBeingViewed === tmpUserBeingViewed} -->
    <!-- {#if userBeingViewed !== undefined} -->
    {#if userBeingViewed}
      <div>{userBeingViewed.username}</div>
      <DisplayAUser aUsername={userBeingViewed.username}/>
      <!-- <DisplayAUser aUsername={sendUsername}/> -->

      <Button type="secondary" on:click={() => sendFriendRequest(userBeingViewed.username)}>Add Friend</Button>
      <!-- {#if user not blocked}
        <Button on:click={() => blockAUser(userBeingViewed.username)}>Add Friend</Button>
        does it have to be friendship IDs? can't i just use username?
        i mean i guess friendship ID is more secure, and also easier in the back
        but if i'm using friendshi ID i need a good way of getting them
      {/if} -->
    <!-- {:else if userBeingViewed !== undefined} -->
    {/if}

    <!-- {#await userBeingViewed}
      <p>... waiting</p>
    {:then}
      <div>{userBeingViewed.username}</div>
      <DisplayAUser aUsername={userBeingViewed.username}/>

      <Button type="secondary" on:click={() => sendFriendRequest(userBeingViewed.username)}>Add Friend</Button>

    {:catch}
      <p>No user to view yet</p>
    {/await} -->
<!-- {#if user not blocked}
        <Button on:click={() => blockAUser(userBeingViewed.username)}>Add Friend</Button>
        does it have to be friendship IDs? can't i just use username?
        i mean i guess friendship ID is more secure, and also easier in the back
        but if i'm using friendshi ID i need a good way of getting them
      {/if} -->
    <!-- {:else if userBeingViewed !== undefined} -->



    <!-- <Button on:click={displayAllUsers}>Get All Users</Button>
    {#if allUsers !== undefined}
      {#each allUsers as user}
        <div>{user.username}</div>
      {/each}
    {/if}

    <br> -->

    <!-- <Button on:click={displayMyFriends}>Get All My Friends</Button>
    {#if myFriends !== undefined}
      <div>{myFriends}</div>
      {#each myFriends as friend}
        <div>{friend}{friend.username}</div>
      {/each}
    {/if} -->


    <!-- <br> <br> -->
    <!-- here i want to list all the requests you and have an accept and a decline button -->

    <!-- {#each requestsRecieved as request} -->

    <!-- <br> <br> -->
    <!-- I want to list all the requests made by this user -->

    <!-- <Button on:click={displayRequestsMade}>Display Requests Made</Button>

    {#if requestsMade !== undefined}
      {#each requestsMade as requestMade}
        <div>{requestMade}</div>
      {/each}
    {/if} -->

  </div>
</div>

<style>

/* ok so i want a 12 column grid with a sidebar */

  div.top-grid{
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    /* max-height: calc(100vh - 30vh); */
    height: 85vh;
    /* margin: 0; */
  }

  div.all-users-sidebar{
    grid-column: 1 / span 2;
    background: white;
  }

  div.a-user{
    /* yea i mean that seems fine... */
    display: inline-block;
    /* somehting about the buttons too, smaller ? */
  }
  div.status{
    font-size: 0.6em;
    font-weight: bold;
  }
  /* selector attributes to get only divs with .a-user */
  /* you gotta be careful with Svelte cuz it tacks classes on to the end of basically all elems! */
  div[class^="a-user"]:hover{
    text-decoration: underline;
    font-weight: bold;
    cursor: pointer;
  }

  div.main-display{
    grid-column: 3 / span 10;
  }


  .error{
    font-size: 0.8em;
    font-weight: bold;
    color: red;
  }
</style>
