
<template>
    <div v-if="!iconMode" class="media-button" @click="openMediaFrame">
        <AppIcon name="image-line"/>
        <span v-if="title">{{ title }}</span>
    </div>

    <div v-else @click="openMediaFrame">
        <AppIcon name="image-line"/>
    </div>
</template>

<script setup>
import { onMounted, watch } from 'vue';
import AppIcon from './Icon.vue';

const props = defineProps({
    multiple: {
        type: Boolean,
        default: false
    },
    iconMode: {
        type: Boolean,
        default: false
    },
    attachments: {
        type: Array,
        default: () => [],
    },
    title: {
        type: String,
        default: 'Add Media'
    },
    actionTitle: {
        type: String,
        default: 'Use This Media'
    },
    icon: {
        type: String,
        default: 'Camera'
    }
})

let preSelectedIds = [];

let mediaFrame = null;
const emit = defineEmits(['onMediaSelected'])

const openMediaFrame = () => {
    if (mediaFrame == null) {
        return
    }
    mediaFrame.open();
}

defineExpose({
    openMediaFrame
})

onMounted(() => {

    if (typeof window.wp.media !== 'function') {
        return
    }


    // Override the default media modal with the custom class
    window.wp.media.view.Modal = window.wp.media.view.Modal.extend({
        className: 'wp-fluent-media-modal', // Add your custom class here
    });

    setUpPreSelectedIds();
    mediaFrame = window.wp.media({
        title: 'Select or Upload Media Of Your Chosen Persuasion',
        button: {
            text: props.actionTitle
        },
        library: {
            type: 'image'
        },
        multiple: props.multiple ? 'add' : false,  // Set to true to allow multiple files to be selected
        is_button: props.is_button,
    });

    setPreselected();
    listenForMediaChange();

})

const isNumeric = (value) => {
    return /^\d+$/.test(value);
}

const setUpPreSelectedIds = () => {
    preSelectedIds = [];
    if (Array.isArray(props.attachments) && props.attachments.length > 0) {
        Object.values(props.attachments).forEach((attachment, index) => {
            if (isNumeric(attachment['id'])) {
                preSelectedIds.push(attachment['id'])
            }
        })
    }
}

const setPreselected = () => {
    mediaFrame.on('open', function () {
        let selection = mediaFrame.state().get('selection');
        preSelectedIds.forEach(function (id) {
            let attachment = window.wp.media.attachment(id);
            if (attachment) {
                selection.add(attachment)
            }
        }); // would be probably a good idea to check if it is indeed a non-empty array
    });
}

const listenForMediaChange = () => {
    mediaFrame.on('select', function () {
        const attachments = mediaFrame.state().get('selection').toJSON()
        emit('onMediaSelected', attachments)
    })
}

watch(() => props.attachments, (first, second) => {
    setUpPreSelectedIds();
});
</script>

<style scoped lang="scss">
.media-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 1rem;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
  gap: 10px;
  justify-content: center;

  .icon {
    font-size: xxx-large;
  }

  span {
    font-size: 14px;
  }

  &:hover {
    background-color: #f5f7fa;
  }
}
</style>
