/**
 * CMSMSExt js functions
 */
(
  function(global)
  {
    /**
     * some helper functions
     */

    /**
     * Checks if a string ends with a specified suffix.
     *
     * @param {string} suffix - The suffix to check.
     * @return {boolean} Returns true if the string ends with the specified suffix, otherwise returns false.
     */
    String.prototype.endsWith = function (suffix)
    {
      return (this.substring(this.lengths - suffix.length) === suffix);
    };

    /**
     * Checks if a string starts with a given prefix.
     *
     * @param {string} prefix - The prefix to check for.
     * @return {boolean} Returns true if the string starts with the prefix, otherwise false.
     */
    String.prototype.startsWith = function(prefix)
    {
      return (this.substring(0, prefix.length) === prefix);
    };

    /**
     * Formats a string in a template like way
     * Usage:
     * 'Added {0} by {1} to your collection'.f(title, artist)
     * 'Your balance is {0} USD'.f(77.7)
     * @type {function(): String}
     */
    String.prototype.format = String.prototype.format = function()
    {
      var s = this,
          i = arguments.length;

      while (i--)
      {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
      }
      return s;
    };
    
    /**
     * CMSMSEXT configuration defaults
     */
    
    var default_CONFIG = {
      action_id: 'm1_',
      ajax_prefix: true,
      action_name: '',
      admin_theme: 'OE',
      toasts_timeout: 5000,
    };
    
    /**
     * @namespace CMSMSEXT
     */
    
    global.CMSMSEXT = global.CMSMSEXT || {};

    /**
     * check for dependencies
     */

    if(typeof  global._ !== 'undefined')
    {
      var _ = global._;

      // Your underscore-dependent code here
    }
    else
    {
      console.log('underscore is not available.');
    }

    if(typeof  global.Backbone !== 'undefined')
    {
      var Backbone = global.Backbone;

      // Your backbone-dependent code here
    }
    else
    {
      console.log('Backbone is not available.');
    }

    if(typeof  global.jSmart !== 'undefined')
    {
      var jSmart = global.jSmart;

      // Your jSmart-dependent code here
    }
    else
    {
      console.log('jSmart is not available.');
    }

    if(typeof  global.UIkit !== 'undefined')
    {
      var UIkit = global.UIkit;
    }
    else
    {
      console.log('UIkit is not available.');
    }

    if(typeof global.jQuery !== 'undefined')
    {
      var $ = global.jQuery;

    }
    else
    {
      console.log('jQuery is not available.');
    }

    if( typeof  global.CMSMSEXT_CONFIG !== 'undefined')
    {
      // Merge default options with user-provided options
      var CMSMSEXT_CONFIG = Object.assign({}, default_CONFIG, global.CMSMSEXT_CONFIG);
      
      //action_id will always be m1_ when in backend context for now so, assume it is
      CMSMSEXT.action_id   = (typeof CMSMSEXT_CONFIG.action_id === 'undefined' ? 'm1_' : CMSMSEXT_CONFIG.action_id);
      CMSMSEXT.action_name = CMSMSEXT_CONFIG.action_name;
      CMSMSEXT.admin_theme = CMSMSEXT_CONFIG.admin_theme;
    }

    CMSMSEXT.VIEW = function(){};

    CMSMSEXT.AJAX = function(){};

    CMSMSEXT.AJAX.init = function()
    {
      /**
       * An AJAX request function meant to dumb down the ajax process quite a bit
       * - data (the params) will be prefixed with the action id to conform with CMSMS own system
       * - typically only url and data will be needed, in some cases not even that
       *
       * this is an internal function
       *
       * @param {string} url - The URL for the request
       * @param {object} data - The data to send with the request
       * @param {function} success - The success callback function
       * @param {function} error - The error callback function
       * @param {function} complete - The complete callback function
       * @param {string} datatype - The data type to expect in the response
       * @param {string} method - The HTTP method (e.g., GET, POST, PUT, DELETE)
       *
       * @deprecated
       */
      var __ajax2 = function (url, data, success, error, complete, datatype, method)
      {
        const defaults = {
          url: '',                // URL for the request
          method: 'GET',          // HTTP method (e.g., GET, POST, PUT, DELETE)
          data: null,             // Data to send with the request
          dataType: 'json',       // Data type to expect in the response (e.g., json, html)
          success: function(data) {
            console.log('Success:', data);
          },                      // Success callback function
          error: function(xhr, status, error) {
            console.error('Error:', status, error);
          },                      // Error callback function
          complete: function(xhr, status) {
            console.log('Request completed with status:', status);
          }                       // Complete callback function
        };
        
        var tmp_options = {
          url: url,
          method: method,
          data: data,
          dataType: datatype,
          success: success,
          error: error,
          complete: complete,
        };
        
        var options = $.extend({}, defaults, tmp_options);
        
        // Prefix each data parameter with action_id
        if(CMSMSEXT.action_id && CMSMSEXT_CONFIG.ajax_prefix)
        {
          const prefixedData = {};
          for(const key in options.data)
          {
            if(options.data.hasOwnProperty(key))
            {
              prefixedData[options.dataPrefix + key] = options.data[key];
            }
          }
          options.data = prefixedData;
        }

        $.ajax(
          {
            method: options.method,
            dataType: options.dataType,
            data: options.data,
            url: options.url,
            success: options.success,
            error: options.error,
            complete: options.complete,
          });
      };
      
      /**
       * An AJAX request function meant to dumb down the ajax process quite a bit
       * - data (the params) will be prefixed with the action id to conform with CMSMS own system
       * - typically only url and data will be needed, in some cases not even that
       *
       * this is an internal function
       *
       * @param options
       */
      var __ajax = function (options)
      {
        const defaults = {
          url: '',                // URL for the request
          method: 'GET',          // HTTP method (e.g., GET, POST, PUT, DELETE)
          data: null,             // Data to send with the request
          dataType: 'json',       // Data type to expect in the response (e.g., json, html)
          success: function(data) {
            console.log('Success:', data);
          },                      // Success callback function
          error: function(xhr, status, error) {
            console.error('Error:', status, error);
          },                      // Error callback function
          complete: function(xhr, status) {
            console.log('Request completed with status:', status);
          }                       // Complete callback function
        };
        
        options = $.extend({}, defaults, options);
        
        console.log(options);
        
        // Prefix each data parameter with action_id
        if(CMSMSEXT.action_id && CMSMSEXT_CONFIG.ajax_prefix)
        {
          const prefixedData = {};
          for(const key in options.data)
          {
            if(options.data.hasOwnProperty(key))
            {
              prefixedData[options.dataPrefix + key] = options.data[key];
            }
          }
          options.data = prefixedData;
        }

        $.ajax(options);
      };
      
      /**
       * the main json ajax function
       * it assumes a bunch of parameter defaults
       *
       * @param url
       * @param data
       * @param success
       * @param error
       * @param complete
       */
      CMSMSEXT.AJAX.cmsms_json_ajax = function(url, data, success, error, complete)
      {
        var options = {
          url: url,
          method: 'POST',
          data: data,
          dataType: 'json',
          success: success,
          error: error,
          complete: complete
        }
        __ajax(options);
      };
      
      /**
       * the main txt ajax function
       * it assumes a bunch of parameter defaults
       *
       * @param url
       * @param data
       * @param success
       * @param error
       * @param complete
       */
      CMSMSEXT.AJAX.cmsms_txt_ajax = function(url, data, success, error, complete)
      {
        var options = {
          url: url,
          method: 'POST',
          data: data,
          dataType: 'text',
          success: success,
          error: error,
          complete: complete
        }
        __ajax(options);
      };
    };

    CMSMSEXT.UTILS = {
      rnd: function() { return Math.random().toString(36).substring(2); }
    };

    CMSMSEXT.VIEW.init = function()
    {
      CMSMSEXT.VIEW.messages_template = '<aside id="helper_message" class="message pagemcontainer" role="status"><p>{0}</p></aside>';
      CMSMSEXT.VIEW.errors_template = '<aside id="helper_error" class="message pageerrorcontainer" role="alert"><p>{0}</p></aside>';
      
      if(UIkit)
      {
        /**
         * notification stuff
         */
        /**
         * @param message
         * @param status
         */
        CMSMSEXT.VIEW.notify = function(message, status)
        {
          // TODO make pos and timeout configurable
          UIkit.notification({
            message: message,
            status: status,
            pos: 'top-right',
            timeout: 5000
          });
        };

        CMSMSEXT.VIEW.notify_success = function(message)
        {
          message = '<div class="uk-alert-success" uk-alert>' + message + '</div>';
          this.notify(message, 'success');
        };

        CMSMSEXT.VIEW.notify_error = function(message)
        {
          message = '<div class="uk-alert-danger" uk-alert>' + message + '</div>';
          this.notify(message, 'danger');
        };

        CMSMSEXT.VIEW.notify_warning = function(message)
        {
          message = '<div class="uk-alert-warning" uk-alert>' + message + '</div>';
          this.notify(message, 'warning');
        };
      }

      if(CMSMSEXT.admin_theme)
      {
        /**
         * taps into the core function to show a message when needed
         * theme dependent OneEleven in this case: OE
         *
         * @param message
         */
        CMSMSEXT.VIEW.core_success_msg = function(message)
        {
          let output = this.messages_template.format(message);
          $('#helper_message').detach();
          $('#oe_mainarea').prepend(output);
          $('#helper_message').hide();
          CMSMSEXT.admin_theme.view.showNotifications();
        };

        /**
         * taps into the core function to show an error when needed
         * theme dependent OneEleven in this case: OE
         *
         * @param message
         */
        CMSMSEXT.VIEW.core_error_msg = function(message)
        {
          let output = this.errors_template.format(message);
          $('#helper_error').detach();
          $('#oe_mainarea').prepend(output);
          $('#helper_error').hide();
          CMSMSEXT.admin_theme.view.showNotifications();
        };
      }
    };

    // Initialize
    document.addEventListener("DOMContentLoaded", function()
    {
      CMSMSEXT.AJAX.init();
      CMSMSEXT.VIEW.init();
    });

  }(this)
);

