/**
 * Add shortcode to editor
 *
 * @param obj
 * @returns {boolean}
 */
function formm_set_shortcode(obj) {
    let selected_value = jQuery('#id-nf-values').val();
    var project_id = jQuery('#id-nf-values').find(':selected').attr('data-project');
    if (selected_value > 0) {
        let formsio_text = jQuery('#post-content-0').text();
        formsio_text = formsio_text + '\n[' + nf_app + ' '+'id="' + selected_value + '"]';
        jQuery('#post-content-0').val(formsio_text);
        jQuery('.block-editor-block-list__layout>p')[0].append(formsio_text);
        var theMessage = jQuery('.wp-editor-area').val();
        var totalShortcode ='<p>'+formsio_text + theMessage+'</p>';
        jQuery('.wp-editor-area').val(totalShortcode);
    }
    return false;
}

/**
 * Get JSON data for select
 */
function form_get_data() {    
    var library_names;
    var token = formsio_getcookie('token');
    var region = parseJwt (token).env;    
    let select = '<select id="id-nf-values" onchange="return formm_set_shortcode(this.value)">' +
        '<option data-project="0" value="0">' + '-' + '</option>';
    var token = formsio_getcookie('token');
    var url1 = 'https://forms.'+region+'.500apps.com/v2/forms?limit=50&order_by=created_date%20desc' + '&token=' + token;
    E_url1= encodeURI(url1);
    var pcors1 = 'https://api.us1.500apps.io/pcors?url='+E_url1;

    jQuery.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("token", token);
    },
    dataType: "json",
    url: 'https://my.'+region+'.500apps.com/pcors?url=https%3A%2F%2Fforms.'+region+'.500apps.com%2Fv2%2Fprojects%3Flimit%3D50%26order_by%3Dcreated_date',
    success: function(data1) {
            library_names = data1;
                    jQuery.ajax({
                    beforeSend: function(request) {
                        request.setRequestHeader("token", token);
                    },
                    dataType: "json",
                    url: url1,
                    success: function(data) {
                        var response = data;
                        let json = response;//JSON.parse(response);                        
                        for( key in library_names){
                            let projectdata = library_names[key];
                            select = select + '<optgroup label="'+projectdata.name+'"</option>';
                            for (key1 in json) {
                                let data = json[key1];
                                if (projectdata.id == data.project_id) {
                                    select = select + '<option data-project="'+data.project_id+'" value="' + data.id + '">' + data.name + '</option>';
                                }
                            }
                        }
                        select = select + '</select>';
                        jQuery('#id-nf-selector').html(select);
                        }
                    });

            }
        });
}

jQuery(document).ready(function ($) {
    form_get_data();
    /** to show other apps **/
    var id1= 0;
    jQuery("a").each(function(idx) {
      if (jQuery(this).attr('href') == "admin.php?page=OtherApps") {
                jQuery(this).addClass('show_popup_forms');
                jQuery(this).attr("href", "#");
                jQuery(this).attr('id', 'show_popup_forms');            
         id1++;
        }
    });

    var formsio_data_text = jQuery('#formsio_data').text();
        jQuery('#formsio_data').html('');
        var decodedData = window.atob(formsio_data_text); 
        jQuery("#formsio_data").append(decodedData);
        jQuery("#formsio_data").attr("style", "display:block");

    /** to close other apps **/
    var modal = document.getElementById("formsModal");
        var btn = document.getElementById("show_popup_forms");
        var span = document.getElementsByClassName("close_forms")[0];
        btn.onclick = function() {
          modal.style.display = "block";
        }
        span.onclick = function() {
          modal.style.display = "none";
        }
        window.onclick = function(event) {
          if (event.target == modal) {
            modal.style.display = "none";
          }
        }        
});
/** to get the cookie **/
function formsio_getcookie(name) {
  var cookie_name = name + "=";
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var extracted_cookie = cookies[i];
    while (extracted_cookie.charAt(0) == ' ') extracted_cookie = extracted_cookie.substring(1, extracted_cookie.length);
    if (extracted_cookie.indexOf(cookie_name) == 0) return extracted_cookie.substring(cookie_name.length, extracted_cookie.length);
}
return null;
}
function parseJwt (token) {
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
  return JSON.parse(jsonPayload);
};
