// This script initializes the invite modal for members to create new shares.
//  It enables users to initate a new sharing invite.

// Flow:
/*
invite()
    - initialize HTML_TEMPLATE
    - initChannels()
        - renders channels and their respective ISLs and creates action buttons next to ISLs
        - setislIDs()
        - initISLs()
    - initRecipient()
    - content.on('submit') -> creates an API request to generate new share(s)

loadOrganizationMembersTable()
    - make api end point call to /api/share_list
        - get all the existing shares for the given member

openSharingModal()
   open the share invite modal to initiate new sharing requests

*/

// eslint-disable-next-line no-unused-vars
var recipientType;
var recipientId;
var isls = [];
var contextISL;
var populationISL;

// eslint-disable-next-line no-unused-vars
var sharing = (() => {
  // eslint-disable-next-line no-unused-vars
  var pageLength = 6;

  // initialize modal template
  var HTML_TEMPLATE =
    `    <form id ="dialog-form">
          <div class="row">
            <div class="col-sm-7">
                <div>
                    <label>Member / Organization</label>
                    <select class="form-control recipient-organization-member" required></select>
                </div>
                <div id="invite-channel-list">
                    <label class="sharingSectionHeader">Channels - Security Layers</label>
                </div>
                <div>
                    <label class="sharingSectionHeader">Message</label>
                    <textarea id="invite-message" class="form-control" rows="6" required></textarea>
                </div>
            </div>
            <div class="col-sm-5" id="isls">
            </div>
          </div>
        </form> `;

  // set ids for Context Dependent and Population ISLs
  function setislIDs() {
    $.each(isls, (index, item) => {
      if (item.indicator_security_level === 'Context Dependent') {
        contextISL = item.indicator_security_level_id;
      } else if (item.indicator_security_level === 'Population') {
        populationISL = item.indicator_security_level_id;
      }
    });
  }

  // render the ISL blurbs with navigation links to indicators which filter the results
  // on indiators page with the given ISL id
  function initISLs(content) {
    content.find('#isls').append(`<div class="form-group">
          <a href="#indicators?isl=${contextISL}" onclick="bootbox.hideAll();"><b>Context Dependent: </b></a>
          <p>Where data represents a clinical decision by the physician or health provider or a shared decision between the
            physician and the patient, measures are categorized as Context Dependent. Explicit consent is required by the physician
            or health provider for permitting views of Context Dependent measures by users that are not members of your clinic.</p>
      </div>
      <div class="form-group">
          <a href="#indicators?isl=${populationISL}" onclick="bootbox.hideAll();"><b>Population: </b></a>
          <p>Measures are categorized as Population where the data represents a population-level intervention and strong evidence
             exists for a standardized intervention across the population. Aggregate data reports for Population categorized measures
             are viewable by non-clinical users at a Division aggregate-level and above without explicit consent from physicians or other health providers.</p>
      </div>`);
  }

  // render the channels and ISLs along with invite buttons next to each ISL under each channel
  function initChannels(content) {
    // Populate a checkbox list with the channels that the initiator is subscribed to.
    api.run({
      name: 'indicator_security_level_list',
      success(d) {
        var ch;
        // for each channel returned, create a checkbox
        $.each(d, (index, item) => {
          // check if the current item is the one the user clicked 'reinvite' on.
          // This one should be prechecked
          // console.log(item);
          isls.push(item);
          if (ch !== item.channel) {
            ch = item.channel;
            content.find('#invite-channel-list').append(`${'<div class="col-sm-12 topChannel">' +
                                '   <label>' +
                                '       <p>'}</p> ` +
                                `       <span>${item.channel}</span>` +
                                '   </label>' +
                                '</div>');
          }
          content.find('#invite-channel-list').append(`${'<div class="col-sm-12 topISL">' +
                              '         <div class="col-sm-8">' +
                              `           <span>${item.indicator_security_level}</span>` +
                              '         </div>' +
                              '         <div>' +
                              '           <input type="button"'}
                                                class="col-sm-4 btn"
                                                id="${item.channel_id}${item.indicator_security_level_id}"
                                                value="Invite"
                                                data_channel_id="${item.channel_id}"
                                                data_channel_name="${item.channel}"
                                                data_security_level_name="${item.indicator_security_level}"
                                                data_security_level_id="${item.indicator_security_level_id}"
                                                onclick="changeSharingStatus('${item.channel_id}${item.indicator_security_level_id}');"
                                            ></input> ` +
                              '         </div>' +
                              '   </div>');
        });

        // if no channels are returned, show a warning message
        if (d.length < 1) {
          content.find('#invite-channel-list').append('<div>' +
                        '   <label>' +
                        '       <p class="text-danger">The member must subscribe to at least one channel to share data.</p>' +
                        '   </label>' +
                        '</div>');
        }
        setislIDs();
        initISLs(content);
      },
    });
  }

  // populate dropdown with the list of available members and organizations
  // with whom new sharing invites could be initiated
  function initRecipient(content) {
    content.find('.recipient-organization-member').select2({

      ajax: api.select2({
        name: 'share_invitees',
        data() {
          return {
            exclude_self: true,
            sharee_id: getOrganizationMemberId(),
            sharee_type: 'member',
          };
        },
        id(d) { return d.invitee_id; },
        text(d) { return `${d.invitee_name}`; },
        optData(d) { return `${d.invitee_type}`; },
        pageLength: 6,
      }),
      minimumInputLength: 2,
      width: '100%',
      allowClear: true,
    });
  }

  function showDialog(content, showSendButton) {
    var sendClass = `btn-primary btn-accept ${showSendButton ? '' : 'hidden'}`;

    bootbox.dialog({
      title: 'Send Sharing Invite',
      message: content,
      buttons: {
        cancel: {
          label: 'Cancel',
        },
        success: {
          label: 'Send',
          className: sendClass,
          callback() {
            $('<input type="submit">').hide().appendTo(content).click()
              .remove();
            return false;
          },
        },
      },
    });
  }

  // based on the invite actions for the ISLs for each of the channels,
  // clicking submit buuton should create a new API request to creata new share(s)
  function submit(content, callback) {
    var channels = [];

    var levels = [];
    var level = {};
    var channel = [];


    recipientId = content.find('.recipient-organization-member').select2('data')[0].id;
    recipientType = content.find('.recipient-organization-member').select2('data')[0].optData;

    $.each(content[0], (index, item) => {
      if ((item.getAttribute('data_channel_name') !== null) && (item.value === 'Invite') && (item.className.indexOf('btn-primary') > 1)) {
        if (channels.channel !== item.getAttribute('data_channel_name')) {
          level = {
            initiator_id: getOrganizationMemberId(),
            initiator_type: 'member',
            recipient_id: recipientId,
            recipient_type: recipientType,
            indicator_security_level: item.getAttribute('data_security_level_name'),
            security_id: item.getAttribute('data_security_level_id'),
            share_status: 'Pending',
            share_status_id: 1,
          };
          levels.push(level);
        } else {
          level = {
            initiator_id: getOrganizationMemberId(),
            initiator_type: 'member',
            recipient_id: recipientId,
            recipient_type: recipientType,
            indicator_security_level: item.getAttribute('data_security_level_name'),
            security_id: item.getAttribute('data_security_level_id'),
            share_status: 'Pending',
            share_status_id: 1,
          };
          levels.push(level);
        }
      }
      if (levels.length > 0) {
        channel.push({
          channel: item.getAttribute('data_channel_name'),
          channel_id: item.getAttribute('data_channel_id'),
          levels,
        });
        if (channel.length > 0) {
          channels.push({ channel, });
        }
      }

      levels = [];
      level = {};
    });

    channels = JSON.stringify(channels[0].channel);
    api.run({
      name: 'share_update',
      data: {
        channels,
        message: content.find('#invite-message').val(),
      },
      success() {
        bootbox.hideAll();

        showMessage('Invitation Sent', '');

        callback();
      },
    });
  }

  // initialize the invite modal
  function invite(callback) {
    var content;
    $.fn.modal.Constructor.prototype.enforceFocus = () => {};

    content = $(HTML_TEMPLATE);

    initChannels(content);
    initRecipient(content);

    // When the user submits the form..
    content.on('submit', (event) => {
      event.preventDefault();
      submit(content, callback);
    });

    // showSendButton = (organization_member_id !== undefined);
    showDialog(content, true); // showSendButton
  }

  return {
    invite(callback) {
      return invite(callback);
    },
  };
});
