import { Component } from '../../../../lib/vues6/vues6.js'

const template = `
<div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" ref="modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" v-if="ready">
            <div class="modal-header">
                <h5 class="modal-title">{{ t['profile.change_photo'] }}</h5>
                <button type="button" class="close" data-dismiss="modal" :aria-label="t['common.close']">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="file" name="image" ref="input" required>
            </div>
            <div class="modal-footer">
                <button
                    class="btn btn-primary"
                    @click="do_upload"
                >{{ t['common.change'] }}</button>
            </div>
        </div>
    </div>
</div>
`

export default class ProfilePhotoUploaderComponent extends Component {
    static get selector() { return 'coreid-profile-photo-uploader' }
    static get template() { return template }
    static get params() { return [] }

    constructor() {
        super()

        this.ready = false
        this.t = {}
    }

    async vue_on_create() {
        this.t = await T(
            'profile.change_photo',
            'common.change',
            'common.close'
        )
    }

    show() {
        this.ready = true
        this.$nextTick(() => {
            $(this.$refs.modal).modal()
        })
    }

    close() {
        $(this.$refs.modal).modal('hide')
    }

    async do_upload() {
        if ( this.$refs.input.files.length < 1 ) return
        const data = new FormData()
        data.append('photo', this.$refs.input.files[0])
        try {
            await axios.post(`/api/v1/profile/me/photo`, data, { // TODO support passed-in user_id
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            })
            this.$emit('upload')
        } catch (e) {
            console.error(e)
        }
    }
}
