<template>
        <h2>Profilinnstillinger</h2>
        <div id = "profilepicture-container">
            <img  width="100" :src="image" alt="profile picture">
        </div>


        <h3>{{this.profile.name}}</h3>
        <button  @click="changeProfile" id="changeUserBtn" class="redBtn">Bytt bruker</button>

    <form @submit.prevent="submit">
            <label for="brukernavn">Profilnavn</label><br>
            <input type="text" required id="brukernavn" v-model="this.updatedProfile.upName"><br>
            <br>
            <h3>Brukertype</h3>
            <input type="radio" id="normal" value="false" name="restrict" v-model="this.updatedProfile.upRestricted">
            <label for="normal"> Standard</label><br>

            <input type="radio" id="restricted" value="true" name="restrict" v-model="this.updatedProfile.upRestricted">
            <label for="restricted"> Begrenset - Kan ikke redigere ukeplan eller handleliste</label><br><br>


            <h3>Profilbilde</h3><br>
            <div id="changeUserImage">

                <div id = "profilepicture-container">
                    <img width="50" :src="image" id = "profile_img_preview" alt="profile picture">
                </div>
                <div>
                    <input @change="updateImg" type="file" accept=".jpeg, .jpg" id="profile_img" name="profile_img"><br><br>
                </div>


            </div>
        <br><br>
            <div id = "submitbuttonBox">
                <button class="greenBtn" @click=" saveUserSettings">Lagre profilendringer</button>
                <button class="darkRedBtn" @click="deleteProfile">Slett brukerprofil</button>
            </div>

            <p id="alert">{{alertMsg}}</p>

        </form>

</template>

<script>
import {mapState, mapStores} from "pinia";
import {Icon} from "@iconify/vue";
import {API} from "@/util/API";
import { useAuthStore } from "@/stores/authStore";
import router from "../router";
export default {
    name: "EditProfile",
    data() {
        return {
            alertMsg:'',
            image: "profile/default_avatar.png",
        }
    },
    computed: {
        ...mapState(useAuthStore, ['profile']),
        ...mapStores(useAuthStore),
        updatedProfile() {
          return {
              upName: this.profile.name,
              upRestricted: this.profile.restricted,
              upImage: "profile/default_avatar.png",
          }
        },
    },
    beforeMount() {
        if(this.profile.profileImageUrl !== ''){
            this.image = this.profile.profileImageUrl;
        }
    },
    methods: {
        changeProfile(){
            router.push("/selectProfile");
        },
        updateImg() {
            this.alertMsg=""
            let file = document.getElementById("profile_img").files[0];
            let fileSize = file.size
            let reader = new FileReader();
            reader.onload = function (ev) {
                document.getElementById("profile_img_preview").src = ev.target.result;
            };
            reader.readAsDataURL(file);
            if(fileSize>524288){ //if image is bigger than 512kB
                this.alertMsg = "Bildet er for stort (" + Math.ceil(fileSize/1024) + "kB) Maksimal bildestørrelse er 512kB"
            }

            if(file.name.split('.jpeg').length===1 && file.name.split('.jpg').length===1 ){
                this.alertMsg="filtypen støttes ikke (bildet må være av type .jpg/.jpeg)"
            }


        },
        async deleteProfile() {
                const id = this.profile.id;
                API.deleteProfile(id).then(() => {
                    router.push('/selectProfile')
                }).catch((_) => {
                    this.alertMsg = "‼️Alle kontoer må ha minst en profil (profil ble ikke slettet)‼️"
                })
        },
        saveUserSettings(){
            const id = this.profile.id;

            let newName = null;
            let newRestricted = this.updatedProfile.upRestricted

            if(this.updatedProfile.upName !== this.profile.name){
                newName = this.updatedProfile.upName
            }

            API.updateProfile(
                id,{
                    name:newName,
                    profileImageUrl:null,
                    isRestricted: newRestricted,
                }
            ).then((savedProfile)=>{
                useAuthStore().setProfile(savedProfile);

                const id = this.profile.id;
                let image = document.getElementById("profile_img").files[0];

                if (typeof image !== 'undefined') {
                    API.uploadProfileImage(image, id)
                        .then((updatedProfile) => {
                            useAuthStore().setProfile(updatedProfile);
                        }).catch(()=> {
                        this.alertMsg = "Bilde kunne ikke bli oppdatert (bildekrav: JPEG mindre enn 512kB)"
                    });
                }
                else {
                    useAuthStore().setProfile(savedProfile);
                    this.alertMsg = "Profil oppdatert."
                    return;
                }
                this.alertMsg = "Profil oppdatert."
            }).catch(error=> {
                console.log(error)

                switch (error.message){
                    case '400':
                    {
                        this.alertMsg = '‼️Det oppsto en feil: Sørg for at det finnes mist en standard profil på kontoen‼️ '
                        break;
                    }
                    case '409':
                    {
                        this.alertMsg = '‼️Det oppsto en feil: Det finnes allerede en bruker med samme navn‼️'
                        break;
                    }
                    default:
                        this.alertMsg = "‼️Det oppsto en feil.‼️"
                }
            })
        },
    }
}

</script>

<style scoped lang="scss">

input[type="radio"] {
  width: 2em;
  height: 2em;
}

#changeUserBtn {
  border: 1px solid black;
}

#profilepicture-container {
  display:flex;
  border-radius:50%;
  width:100px;
  height: 100px;
  background-color: white;
  justify-content: center;
  align-items: center;
  border: 3px solid base.$grey;
}

#changeUserImage {
    display:flex;
}

img {
  border-radius: 50%;
}

#changeUserImage #profilepicture-container {
    width: 50px;
    height: 50px;
}

#submitbuttonBox {
    display:flex;
    justify-content: space-between;
}

input[type=file]::file-selector-button {
  background-color: base.$light-green;
  color: base.$white;
  border: none;
  font-weight: bold;
  padding: 8px 14px;
  width: 50%;
  border-radius: 10px;
  cursor: pointer;
  margin: 10px;
  transition: color .2s;
}

input[type=file]::file-selector-button:hover {
  background-color: base.$light-green-hover;
}



/*--General--*/
form {
   background-color: base.$grey;
   color: black;
   align-content: end;
   padding: 2em;
   margin-top: 2em;
   margin-bottom: 2em;
 }

input[type="text"],
input[type="password"]{
  width: 100%;
  padding: .5em;
}

button {
  color: black;
  border: 1px solid black;
  margin: 1em;
  padding:.9em;
  font-weight: bold;
}
.redBtn {
  background-color: base.$red;
  border:none;
  color:white;
}

.redBtn:hover {
  background-color: base.$red-hover;
}

.darkRedBtn {
  background-color: darkred;
  border:none;
  color:white;
}
.darkRedBtn:hover {
  background-color: base.$darkred-hover;
}

.greenBtn{
  background-color: base.$green;
  border:none;
  color:white;
}
.greenBtn:hover{
  background-color: base.$green-hover;
}

.infoText {
  background-color: white;
  padding: .5em;
  margin: .4em;
}

#alert {
  display: flex;
  width:100%;
  justify-content: center;
  font-weight: bold;
}
</style>