Vue.component('patientFiles', {

    props: [
        'routes',
        'events',
    ],

    data: function() {
        return {
            records: [],
            filteredRecords: [],
            loading: false,
            editMode: false,
            errors: {},
            success: false,
            display: 5,
            defaultFileRecord: {
                id: null,
                title: '',
                type: 'file',
            },
            record: {},
            deleteIndex: -1,
            todayDate: null,
            showingAll: false,
            types: [],
            filterOpen: false,
            filterApplied: false,
            imageExtensions: [],
            filter: {
                types: [],
            }
        };
    },

    mounted: function() {
        this.init();
    },

    computed: {
        canShowAll() {
            if (!this.records.length) {
                return false;
            }
            if (this.showingAll) {
                return false;
            }
            if (this.filterApplied) {
                return false;
            }
            return this.records.length > this.display;
        },
        filterTypes() {
            return this.filter.types;
        }
    },

    watch: {
        events(stack) {
            // Because there may be more than one event at a time, loop through new events
            for (let i = this.eventIndex; i < stack.length; i++) {
                let event = stack[i];
                if (event.name === 'bpTrackUpdated') {
                    this.load();
                }
            }
            // Update event index so that we don't process already processed events
            this.eventIndex = stack.length;
        },
        filterTypes () {
            this.runFilter();
        }
    },

    methods: {
        init() {
            this.record = { ...this.defaultFileRecord };
            this.load();
        },
        load() {
            this.loading = true;
            let vm = this;

            this.$http.post(this.routes['admin-patient-files-load'], [])
                .then((response) => {

                    const data = response.data;

                    vm.records = data.files;
                    vm.types = data.types;
                    vm.todayDate = data.todayDate;
                    vm.imageExtensions = data.imageExtensions;
                    vm.loading = false;
                    vm.bindImageModal();
                    vm.runFilter();
                });
        },
        typeName(type) {
            if (!type.length) {
                return '-';
            }
            return this.types[type];
        },
        editRecord(record) {
            this.editMode = true;
            this.record = record ?
                record :
                { ...this.defaultFileRecord };
            $('#fileDate').val(this.todayDate);
        },
        cancel() {
            this.editMode = false;
        },
        store() {
            if (this.loading) {
                return;
            }
            this.errors = {};
            this.success = false;
            this.loading = true;

            this.record.date_provided = $('#fileDate').val();
            let formData = new FormData();
            formData.append('file', document.getElementById('patientFile').files[0]);
            Object.keys(this.record).forEach(key => {
                formData.append(key, this.record[key]);
            });

            let vm = this;

            const headers = { 'Content-Type': 'multipart/form-data' }
            this.$http.post(this.routes['admin-patient-files-store'], formData, headers)
                .then((response) => {

                    const data = response.data;

                    if (data.errors) {
                        vm.errors = data.errors;
                        this.loading = false;
                        return;
                    }
                    if (data.success) {
                        vm.success = data.success;
                    }
                    vm.record = { ...vm.defaultFileRecord };
                    vm.editMode = false;
                    vm.load();
                    vm.emitEvent('filesUpdated');
                });
        },
        showConfirmDeletion(index) {
            this.deleteIndex = index;
        },
        deleteRecord(id) {
            if (this.loading) {
                return;
            }
            this.errors = {};
            this.success = false;
            this.loading = true;

            let vm = this;

            this.$http.post(this.routes['admin-patient-files-delete'], {
                id: id,
            })
                .then((response) => {

                    const data = response.data;

                    if (data.errors) {
                        vm.errors = data.errors;
                        this.loading = false;
                        return;
                    }
                    if (data.success) {
                        vm.success = data.success;
                    }
                    vm.showConfirmDeletion(-1);
                    vm.load();
                    vm.emitEvent('filesUpdated');
                });
        },
        showAll() {
            this.showingAll = true;
            this.bindImageModal();
        },
        bindImageModal() {
            this.$nextTick(function () {
                $('.bpTrackImage').mtcOverlay();
            });
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        },
        toggleFilter() {
            this.filterOpen = !this.filterOpen;
        },
        showRow(index) {
            if (this.showingAll) {
                return true;
            }
            if (this.filterApplied) {
                return true;
            }
            return index + 1 <= this.display;
        },
        runFilter() {
            this.filterApplied = false;
            this.filteredRecords = [];
            if (this.filter.types.length === 0) {
                this.filteredRecords = this.records;
                return;
            }
            for (let i = 0; i < this.records.length; i++) {
                if (this.filter.types.includes(this.records[i].type)) {
                    this.filteredRecords.push(this.records[i]);
                }
            }
            this.filterApplied = true;
        },
        isImage(extension) {
            return this.imageExtensions.includes(extension);
        }
    },
});
