<template>
<div class="page settings">
<h2>Settings</h2>

<section class="form inputs">
<h3>Avatar</h3>
<canvas class="displayer" width="200" height="200" ref="avatar"></canvas>
<input type="file"
@change="e => changeAvatar(e.target.files[0])"
/>
<button @click="uploadAvatar">Upload</button>
<label class="error">{{avatarError}}</label>
</section>

<section class="form inputs letterhead">
<h3>Letterhead</h3>
<canvas class="displayer" height="200" ref="letterhead"></canvas>
<input type="file"
@change="e => {setLetterhead(e.target.files[0])}"
/>
<button @click="uploadLetterhead">Upload</button>
<label class="error">{{letterheadError}}</label>
</section>

<section class="form inputs special">
<h3>Profile</h3>
<label for="">First Name</label>
<input type="text" v-model="user.firstName">
<label for="">Last Name</label>
<input type="text" :value="user.lastName">
<label for="">NMLS ID</label>
<input type="text">
<label for="">Branch ID</label>
<input type="text" :value="user.branchId">

<select id="" name="" :value="user.country">
	<option value="USA">USA</option>
	<option value="Canada">Canada</option>
</select>

<button @click="saveProfile">Save</button>
</section>

<section class="form inputs special">
<h3>Reset Password</h3>
<label for="">Old Password</label>
<input type="password" v-model="oldPass">
<label for="">New Password</label>
<input type="password" v-model="newPass">
<label for="">Confirm Password</label>
<input type="password" v-model="confirmPass">
<button
:disabled="!(oldPass && newPass && confirmPass)"
@click="changePassword">Save</button>
<label class="error">{{passError}}</label>
</section>

<Dialog v-if="ready" @close="() => ready = false">
<h3>Confirm your current password to save changes.</h3>
<input type="text">
<button>Confirm</button>
</Dialog>

</div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue"
import Dialog from "./dialog.vue"

let avatar = ref(null) // the canvas element
let letterhead = ref(null) // the canvas element
let ready = ref(false)
let avatarChanged = ref(false)
let avatarError = ref('')
let letterheadError = ref('')
let passError = ref('')
let oldPass = ref('')
let newPass = ref('')
let confirmPass = ref('')
const props = defineProps(['user', 'token'])
const emit = defineEmits(['updateAvatar', 'updateLetterhead'])
let user = Object.assign({}, props.user)

function save() {
}

function check() {
	ready.value = true
}

function uploadAvatar() {
    avatar.value.toBlob(b => {
        fetch(`/api/user/avatar`,
	    {method: 'POST',
	        body: b,
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
        }).then(resp => {
            if (resp.ok) {emit('updateAvatar')}
        })
    })
}

function uploadLetterhead() {
    letterhead.value.toBlob(b => {
        fetch(`/api/user/letterhead`,
	    {method: 'POST',
	        body: b,
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
        }).then(resp => {
            if (resp.ok) {emit('updateLetterhead')}
        })
    })
}

function setLetterhead(f) {
    const validTypes = ['image/jpeg', 'image/png']
    
    if (!validTypes.includes(f.type)) {
        letterheadError.value = 'Image must be JPEG of PNG format'
        return
    }
        fetch(`/api/letterhead`,
	    {method: 'POST',
	        body: f,
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
        }).then(resp => {
            if (resp.ok) {
                resp.blob().then(b => changeLetterhead(b))        
            } else {
                resp.text().then(e => letterheadError.value = e)
            }
        })
}

function changeAvatar(blob) {
    const validTypes = ['image/jpeg', 'image/png']
    
    if (!validTypes.includes(blob.type)) {
        avatarError.value = 'Image must be JPEG of PNG format'
        return
    }
    
    avatarError.value = ''
    
    createImageBitmap(blob,
    {resizeWidth: 200, resizeHeight: 200, resizeQuality: 'medium'}).
    then((img) => {
        avatar.value.getContext("2d").drawImage(img, 0, 0, 200, 200)
    })
}

function changeLetterhead(blob) {
    const validTypes = ['image/jpeg', 'image/png']
    
    if (!validTypes.includes(blob.type)) {
        letterheadError.value = 'Image must be JPEG of PNG format'
        return
    }
    
    createImageBitmap(blob).
    then((img) => {
        let ctx = letterhead.value.getContext("2d")
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
        ctx.drawImage(img, 0, 0)
    })
}

function saveProfile() {
    console.log(user.firstName)
    fetch(`/api/user`,
	    {method: 'PATCH',
	        body: JSON.stringify(user),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
        }).then(resp => {
            if (resp.ok) {}
        })
}

function changePassword(f) {
        fetch(`/api/user/password`,
	    {method: 'POST',
	        body: JSON.stringify({
	            old: oldPass.value,
	            new: newPass.value,
	            confirm: confirmPass.value,
	        }),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
        }).then(resp => {
            if (resp.ok) {
                resp.blob().then(b => {
                    oldPass.value = ""
                    newPass.value = ""
                    confirmPass.value = ""
                    passError.value = ""
                })        
            } else {
                resp.text().then(e => passError.value = e)
            }
        })
}

watch(props.user, (u) => {
    if (props.user.avatar) {
       changeAvatar(props.user.avatar) 
    }
    
    if (props.user.letterhead) {
       changeLetterhead(props.user.letterhead) 
    }
}, {immediate: true})

</script>
