// Page script for sendMessage.html. Bootstrapping (auth cookie check, /info
// fetch, header rendering, active-nav highlight) all live in js/app.js;
// this file just wires the compose form.

var modal = document.querySelector('.modal');
var overlay = document.querySelector('.overlay');

var message = new EasyMDE({
    element: document.getElementById('my-text-area'),
    toolbar: [
        'bold', 'italic', '|',
        'heading-1', 'heading-2', 'heading-3', '|',
        'code', 'unordered-list', 'ordered-list', 'link', 'quote', '|',
        'preview'
    ],
    maxHeight: '260px',
});

CollabCentral.init(function (ctx) {
    // User is authenticated and authorized. Reveal the form + populate the
    // group selectors from the backend.
    document.getElementById('formPanel').classList.remove('hidden');
    loadFavoriteGroups(ctx.appName);
    loadNewGroups(ctx.appName);
});

document.getElementById('sendMessage').onsubmit = function (event) {
    event.preventDefault();
    var appName = CollabCentral.appName;
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function () {
        if (this.readyState === this.DONE && this.status === 200) {
            var result = JSON.parse(xhttp.response);
            var scheduled = document.getElementById('scheduledFor').value;
            var text = 'This message will be sent to <strong>' + result.memberList.length + '</strong> recipient(s).<br><br>';
            if (scheduled) {
                text += 'Scheduled for ' + CollabCentral.escapeHtml(scheduled) + '.';
            } else {
                text += 'It will be sent immediately once you confirm.';
            }
            document.getElementById('modalMessage').innerHTML = text;
            openModal();
        }
    };

    var formData = new FormData();
    formData.append('uploadImage', document.getElementById('uploadImage').files[0]);
    formData.append('message', message.value());
    formData.append('uploadCSV', document.getElementById('uploadCSV').files[0]);
    formData.append('appName', appName);

    var selectedGroups = [];
    for (var group of document.querySelector('#favGroups').getSelectedOptions()) {
        selectedGroups.push(group.value);
    }
    for (var group of document.querySelector('#newGroups').getSelectedOptions()) {
        selectedGroups.push(group.value);
    }
    formData.append('groups', selectedGroups);
    formData.append('scheduledFor', document.getElementById('scheduledFor').value);

    xhttp.open('POST', '/CollabCentral/' + appName + '/jobs/edit');
    xhttp.send(formData);
};

function showImagePreview(event) {
    if (!event.target.files || !event.target.files.length) return;
    var src = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById('file-ip-1-preview');
    preview.src = src;
    preview.style.display = 'block';
}

function loadFavoriteGroups(appName) {
    var el = document.getElementById('favGroups');
    fetch('/CollabCentral/' + appName + '/user/groups/list')
        .then(function (res) { return res.json(); })
        .then(function (groups) {
            for (var i = 0; i < groups.length; i++) {
                var option = document.createElement('option');
                option.text = groups[i].name;
                option.value = groups[i].id;
                el.add(option);
            }
            VirtualSelect.init({ ele: '#favGroups' });
        });
}

function loadNewGroups(appName) {
    var el = document.getElementById('newGroups');
    fetch('/CollabCentral/' + appName + '/user/groups/find')
        .then(function (res) { return res.json(); })
        .then(function (groups) {
            for (var i = 0; i < groups.length; i++) {
                var option = document.createElement('option');
                option.text = groups[i].displayName;
                option.value = groups[i].id;
                el.add(option);
            }
            VirtualSelect.init({ ele: '#newGroups' });
        });
}

function submit() {
    var appName = CollabCentral.appName;
    var scheduled = document.getElementById('scheduledFor').value;
    var url = scheduled
        ? '/CollabCentral/' + appName + '/jobs/schedule'
        : '/CollabCentral/' + appName + '/jobs/runNow';

    fetch(url, { method: 'POST', redirect: 'follow' })
        .then(function (response) {
            clearForm();
            if (response.redirected) window.location.href = response.url;
        })
        .catch(function (err) {
            console.error('Submit failed:', err);
        });

    closeModal();
}

function continueEditing() { closeModal(); }

function openModal() {
    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
}

function closeModal() {
    modal.classList.add('hidden');
    overlay.classList.add('hidden');
}

overlay.addEventListener('click', closeModal);

function clearForm() {
    document.getElementById('uploadImage').value = '';
    message.value('');
    document.getElementById('uploadCSV').value = '';
    document.getElementById('scheduledFor').value = '';
    var preview = document.getElementById('file-ip-1-preview');
    preview.removeAttribute('src');
    preview.style.display = 'none';
}
