<script lang="ts">

  import Card from '../../pieces/Card.svelte';
  import {onMount} from 'svelte';
  import { push } from 'svelte-spa-router';
  import Button from '../../pieces/Button.svelte';

  let user;
  let avatar, newAvatar;
  let uploadAvatarSuccess = false;

  // tbh i might not need this...
  let set = { username: '', tfa: false };
  let nameTmp;  // annoying...
  const errors = { username: '', checkbox: '', avatar: ''};
  let success = {username: '', avatar: '' };

  onMount( async() => {
    user = await fetch('http://transcendance:8080/api/v2/user')
      .then( (x) => x.json() );
    // do a .catch?

    if (user === undefined) {
      console.log('User did not load, something more official should prolly happen')
    }
    // i don't unerstand why this is necessary but it really doesn't like it otherwise
    nameTmp = user.username;
    console.log(user.username)

    set.tfa = user.isEnabledTwoFactorAuth;

    // tmp
    // console.log('this is what is in the avatar before fetch')
    // console.log(avatar)

    await fetch("http://transcendance:8080/api/v2/user/avatar", {method: "GET"})
		  .then(response => {return response.blob()})
		  .then(data => {
		  	const url = URL.createObjectURL(data);
		  	avatar = url;
	  	})
      .catch(() => errors.avatar = 'Sorry your avatar could not be loaded' );

      // .then(() => errors.avatar = '' ) // unnecessary i think cuz in on mount...

      // tmp
      // console.log('this is what is in the avatar')
      // console.log(avatar)
      // console.log('this is what is in the NEW Avatar')
      // console.log(newAvatar)
    })

  const settingsHandler = async() => {
    // I don't really care which i use at this point...
    // if (set.username === nameTmp) {
    if ((set.username.trim() === '') && set.tfa === user.isEnabledTwoFactorAuth) {
      errors.username = 'Invalid new username';
      return;
    }
	else if ((set.username.trim() === '') && set.tfa !== user.isEnabledTwoFactorAuth) {
		set.username = user.username
	}
	else {
      errors.username = '';
    }
	await fetch('http://transcendance:8080/api/v2/user',{
		method: 'PATCH',
		headers: {
		'Content-Type': 'application/json'
		},
		body: JSON.stringify({
		"username": set.username,
		"isEnabledTwoFactorAuth":  set.tfa
		})
	})
	.then((response) => {
		if (response.status === 200)
			success.username = "Your changes have been saved"
		else if (response.status === 201)
			push("/2fa")
		else
			errors.username = "Something went wrong"
		}
	)
	.catch((err) => errors.username = err)

        // .then((result) => console.log(result))
        // .then(() => console.log('successful sub of new settings'))
  };

  const uploadAvatar = async() => {
    errors.avatar = '';
    if (newAvatar === undefined) {
      errors.avatar = 'You need to pick a file.'
      return;
    }
	const data = new FormData();
	data.append("file", newAvatar[0]);

// tmp
	console.log(data);

	await fetch("http://transcendance:8080/api/v2/user/avatar",
	{
		method : 'POST',
		body : data,
	})
	.then(() => uploadAvatarSuccess = true ) // for some reason it needs to be a function, i think a TS thing, not a promis otherwise
	.then(() => success.avatar = 'Your changes have been saved')
	.catch(() => errors.avatar = 'Sorry failed to upload your new Avatar' );
	await fetch("http://transcendance:8080/api/v2/user/avatar", {method: "GET"})
		.then(response => {return response.blob()})
		.then(data => {
			const url = URL.createObjectURL(data);
			avatar = url;
		})
	.catch(() => errors.avatar = 'Sorry your avatar could not be loaded' );
	}

</script>


<main>
  <h2>Look! You can change stuff</h2>
  <div class="cards">
    <Card>
      <form on:submit|preventDefault={settingsHandler}>
        <div class="form-field">
          <div class="label">New Username</div>
          <!-- it really hates {user.username} and ${user.username} -->
          <!-- <input type="text" placeholder="current username: ${user.username}" bind:value={set.username}> -->
          <input type="text" placeholder="current username: {nameTmp}" bind:value={set.username}>
		      <div class="success">{success.username}</div>
          <div class="error">{errors.username}</div>
        </div>
        <div class="form-field">
          <div class="label inline-check">Set Two Factor Authentication</div>
          <input class="inline-check" type="checkbox" bind:checked={set.tfa}>
          <div class="error">{errors.checkbox}</div>
        </div>
        <Button type="secondary">Update Settings</Button>
      </form>
    </Card>

    <Card>
      <!-- ok so it can't actually show us the file we upload until we've uploaded it... -->
      {#if avatar !== undefined}
        <img class="avatar" src={avatar} alt="your avatar"/>
      {/if}
      <form on:submit|preventDefault={uploadAvatar}>
        <!-- not convinced this has any utility. -->
        <!-- <input type="text" bind:value={postVar} placeholder={"choose your file"}/> -->
        <div class="form-field">
          <div class="label">Pick a new Avatar</div>
          <input type="file" bind:files={newAvatar}/>
          <div class="error">{errors.avatar}</div>
        </div>
        <Button type={newAvatar === undefined ? "primary" : "secondary"}>Upload Avatar</Button>
      </form>
    </Card>
  </div>

</main>



<style>

  main {
    text-align: center;
    /* display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 20px; */
  }

  div.cards{
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 20px;
    /* text-align: center; */
  }

  img {
    /* we want the image to display as the same size no matter the resolution */
    /* max-width: fit-content; */
    /* max-width: 100px; */
    width: 60px;
    /* ok this works but i'm guessing i'll need to add some @media ... */
    /* padding: 10px; */
    /* this doesn't work either when nothing loads and it's just the words... don't love that */
  }

  form {
    /* max-width: 500px; */
    text-align: center;
  }

  .form-field {
    padding: 10px;
  }

  .label {
    font-weight: bold;
  }

  .inline-check{
    display: inline;
  }


  .error{
    font-size: 0.8em;
    font-weight: bold;
    color: red;
  }

  .success{
	font-size: 0.8em;
    font-weight: bold;
    color: green;
  }

</style>
