<!--
  - Copyright (c) 2022.
  - Author Peter Placzek (tada5hi)
  - For the full copyright and license information,
  - view the LICENSE file that was distributed with this source code.
  -->

<script>
import Vue from "vue";
import { Cropper } from 'vue-advanced-cropper';

import UserAvatar from "@/components/user/UserAvatar";
import {editUserImage} from "@/domains/user/api";
import {transformDataURIToBlob} from "@/modules/utils";

export default {
    components: {UserAvatar, Cropper},
    props: {
        user: {
            type: Object,
            default: undefined
        },
        parentEditing: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            editing: false,
            loading: false,
            fileInput: undefined,
            fileCropped: undefined,

            coordinates: {

            },
            visibleArea: {

            }
        }
    },
    methods: {
        toggleEdit() {
            this.editing = !this.editing;

            this.$emit('editing', this.editing);
        },
        selectAvatarFile(e) {
            if(this.loading) return;

            this.loading = true;

            const files = e.target.files || e.dataTransfer.files;
            if (!files.length) {
                this.loading = false;
                return;
            }

            const reader  = new FileReader();
            reader.onload = (readerEvent) => {
                this.fileInput = readerEvent.target.result;
                this.loading = false;

                this.$refs['avatarImageInput'].value = '';
                this.$refs['avatarImageResize'].show();
            };
            reader.readAsDataURL(files[0]);
        },
        handleFileSelected(data) {
            this.fileCropped = data.canvas.toDataURL('image/png');
        },
        async handleOk() {
            try {
                const cropperResult = this.$refs['cropper'].getResult();

                const user = await editUserImage(this.user.id, 'avatar', transformDataURIToBlob(this.fileInput), {
                    coordinates: cropperResult.coordinates,
                    visibleArea: cropperResult.visibleArea
                });

                if(this.user.id === this.$store.getters['auth/userId']) {
                    await this.$store.dispatch('auth/triggerSetUserProperty', {property: 'avatar', value: user.avatar})
                }

                this.$emit('updated', {
                    avatar: user.avatar
                });
            } catch (e) {
                this.$bvToast.toast(e.message, {
                    variant: 'warning'
                })
            }
        }
    },
    computed: {
        image() {
            if(typeof this.fileCropped !== 'undefined') {
                return this.fileCropped;
            }

            if(typeof this.fileInput !== 'undefined') {
                return this.fileInput;
            }

            return this.user.avatar;
        }
    }
}
</script>
<template>
    <div class="header-container">
        <div class="container">
            <div class="d-flex flex-row flex-wrap">
                <div class="header-avatar">
                    <div class="user-avatar">
                        <user-avatar :name="user.name" :size="120" :avatar="image" :email="user.email" />
                        <!-- <img :src="avatarImage"  alt=""/> -->
                        <div class="avatar-edit active" v-if="editing || parentEditing">
                            <div class="box w-100">
                                <label for="avatar-image">
                                    <i class="fa fa-camera d-block fs-h3"></i>
                                    Avatar editieren
                                </label>
                                <input id="avatar-image" ref="avatarImageInput" @change="selectAvatarFile" class="hide" type="file">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="header-meta align-self-center">
                    <h2 class="text-light mb-1">{{ user.name }}</h2>

                    <button :class="{'active': editing || parentEditing}" type="button" class="btn btn-outline-secondary btn-sm" @click="toggleEdit">
                        <i class="fas fa-photo-video"></i>
                    </button>
                </div>
            </div>
        </div>
        <b-modal
            size="lg"
            ref="avatarImageResize"
            button-size="sm"
            title-html="<i class='fab fa-photo'></i> Avatar"
            :no-close-on-backdrop="true"
            :no-close-on-esc="true"
            @ok="handleOk"
        >
            <cropper
                ref="cropper"
                class="cropper"
                :src="fileInput"
                :stencil-props="{
                  aspectRatio: 1
                }"
                :min-width="100"
                :min-height="100"
                @change="handleFileSelected"
            ></cropper>
            <template #modal-footer="{ ok, cancel, hide }">
                <button type="button" class="btn btn-xs btn-primary" @click.prevent="ok">
                    Speichern
                </button>
                <button @click="hide" type="button" class="btn btn-xs btn-secondary" @click.prevent="cancel">
                    Schließen
                </button>
            </template>
        </b-modal>
    </div>
</template>
<style>
.header-container {
    bottom: 15px;
    position: absolute;
    width: 100%;

    text-align: left;
}

.btn-outline-secondary {
    color: #eee;
}

.header-avatar {
    width: 120px;
    z-index: 2;
}
.header-meta {
    margin-left: 20px;
    z-index: 2;
}

.user-avatar {
    position: relative;
}

.user-avatar img {
    height: 100%;
    width: 100%;
    border-radius: 50%;
}

.avatar-edit {
    position: absolute;
    top: 0px;
    right: 0px;
    left: 0px;
    text-align: center;
    height: 100%;
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0% 0%;
    transition: all 0.2s ease-in 0s;
    display: none;
    z-index: 1;
    color: #dedede;
}

.avatar-edit {
    z-index: 3;
}

.avatar-edit.active {
    display: block;
}
.avatar-edit .box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.avatar-edit input[type=file] {
    display: none;
}

.avatar-edit {
    border-radius: 50%;
}

.avatar-edit label {
    cursor: pointer;
}
</style>
