<template>
    <div>
        <cropper
            class="cropper"
            ref="cropper"
            :src="image"    
            :auto-zoom="false"     
            :stencil-props="{           
                aspectRatio: 1,
                scalable: true
            }"
                
            image-restriction="stencil"
        />
        <div class="loc-buttons">
            <span @click="cancelButtonClicked" class="loc-btn"><p><b-icon icon="x"/></p></span>
            <span @click="rotateButtonClicked(90)" class="loc-btn"><p><b-icon icon="arrow-clockwise"/></p></span>
            <span @click="rotateButtonClicked(-90)" class="loc-btn"><p><b-icon icon="arrow-counterclockwise"/></p></span>
            <span @click="flipButtonClicked" class="loc-btn"><p><b-icon icon="arrow-left-right"/></p></span>
            <span @click="okButtonClicked" class="loc-btn"><p><b-icon icon="check2"/></p></span>
        </div>
    </div>
</template>

<script>
import { Cropper } from 'vue-advanced-cropper';
import 'vue-advanced-cropper/dist/style.css';

export default {
	components: {
		Cropper,
	},
    props:{
        image: {
            type: String,
            default: ""
        }
    },
	data() {
		return {
        }
	},
	methods: {
        async okButtonClicked(){            
            const blob = await this.getBlobFromCanvas();
            this.closeImageCrop(blob);
        },
        cancelButtonClicked(){
            this.closeImageCrop(null);
        },
        rotateButtonClicked(angle){
            this.$refs.cropper.rotate(angle);
        },
        flipButtonClicked(){
            this.$refs.cropper.flip(true, false);
        },
        async getBlobFromCanvas(){
            const { canvas } = this.$refs.cropper.getResult(); 
            
            const resizedCanvas = document.createElement('canvas');
            resizedCanvas.height = 600;
            resizedCanvas.width = 600;
            const resizedCanvasContext = resizedCanvas.getContext('2d');
            resizedCanvasContext.drawImage(canvas, 0, 0, 600, 600);

            const getBlob = (can) => {
                return new Promise((resolve, reject) => { can.toBlob((blob) => { resolve(blob) }, 'image/jpeg', 0.9); });
            }
            const file = await getBlob(resizedCanvas);
            return file;
        }
	},
}
</script>

<style lang="css">
.cropper {
	height: 100%;
	background: #DDD;
}
.loc-buttons{
    position: fixed;
    bottom: 20px;
}
.loc-btn{     
    display: inline-block;
    height: 70px;
    width: calc(100vw/5);
    background: transparent;
}
.loc-btn p{
    position: relative;
    color: #fff;
    font-size: 40px;    
    top: -23px;
    left: 12px;
}
</style>