<!--
  - 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 UserAvatarContainer from "@/components/user/UserAvatarContainer";
import {editUserImage} from "@/domains/user/api";
import {transformDataURIToBlob} from "@/modules/utils";
import { Cropper } from 'vue-advanced-cropper';

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

            },
            visibleArea: {

            }
        }
    },
    methods: {
        toggleEdit() {
            this.editing = !this.editing;
        },
        selectFile(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['coverImageInput'].value = '';
                this.$refs['coverImageResize'].show();
            };
            reader.readAsDataURL(files[0]);
        },
        handleFileSelected(data) {
            this.fileCropped = data.canvas.toDataURL('image/png');

            for(let key in data.coordinates) {
                if(!data.coordinates.hasOwnProperty(key)) continue;
                Vue.set(this.coordinates, key, data.coordinates[key]);
            }

            for(let key in data.visibleArea) {
                if(!data.visibleArea.hasOwnProperty(key)) continue;
                Vue.set(this.visibleArea, key, data.visibleArea[key]);
            }
        },
        async handleOk() {
            try {
                const user = await editUserImage(this.user.id, 'cover', transformDataURIToBlob(this.fileInput), {
                    coordinates: this.coordinates,
                    visibleArea: this.visibleArea
                })

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

                this.$emit('updated', {
                    cover: user.cover
                });
            } catch (e) {
                console.log(e);
            }
        }
    },
    computed: {
        image() {
            if(typeof this.fileCropped !== 'undefined') {
                return this.fileCropped;
            }

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

            if(!!this.user.cover) {
                if (typeof this.user.cover.large !== 'undefined') {
                    return this.$nuxt.$config.apiUrl + '/' + this.user.cover.path + this.user.cover.large;
                } else if (typeof this.user.cover.original !== 'undefined') {
                    return this.$nuxt.$config.apiUrl + '/' +  this.user.cover.path + this.user.cover.original;
                }
            }

            return '';
        }
    }
}
</script>
<template>
    <div class="cover-container">
        <div class="cover-edit active" v-if="editing" style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;">
            <div class="box">
                <label for="cover-image">
                    <i class="fa fa-camera"></i> Cover editieren (1440w x 400h)
                </label>
                <p>
                    Cover Bilder werden größer und kleiner basierend auf eurer Gerätebreite.
                </p>
            </div>
            <input class="hide" ref="coverImageInput" @change="selectFile" id="cover-image" type="file">
        </div>
        <slot name="header-container" :user="user" :toggleEdit="toggleEdit"></slot>

        <div class="cover" :style="{'background-image': 'url('+image+')'}" style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;">
            <div class="overlay" style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;"></div>
        </div>
        <b-modal
            size="lg"
            ref="coverImageResize"
            button-size="sm"
            title-html="<i class='fab fa-photo'></i> Cover"
            :no-close-on-backdrop="true"
            :no-close-on-esc="true"
            @ok="handleOk"
        >
            <cropper
                class="cropper"
                :src="fileInput"
                :stencil-props="{
                  aspectRatio: 36/10
                }"
                :min-width="360"
                :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>
.cover-container {
    height: 350px;
    position:relative;
}

.cover {
    height: 350px;
    text-align: center;
    position: relative;
    background-position: center center;
    background-size: cover;
}

.cover .overlay {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    background-color: rgba(0, 0, 0, 0.35);
}

.cover .header-meta h2 {
    margin-bottom: 15px;
}

.cover-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;
}

.cover-edit.active {
    display: block;
}

.cover-edit .box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.cover-edit label {
    padding: 14px 50px;
    color: #FFF;
    background: transparent none repeat scroll 0% 0%;
    border: 1px solid #FFF;
    font-family: "klavika",Helvetica,Arial,sans-serif;
    cursor: pointer;
}

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

</style>
