// Generated by CoffeeScript 1.7.1
(function() {
  var fFailedRequest, fOnLoad, strPublicKey,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  strPublicKey = '';

  fFailedRequest = function(msg) {
    return function(err) {
      if (err.status === 401) {
        return window.location.href = 'forge?page=forge_rule';
      } else {
        $('#info').text(msg);
        return $('#info').attr('class', 'error');
      }
    };
  };

  $.post('/usercommand', {
    command: 'get_public_key'
  }).done(function(data) {
    return strPublicKey = data.message;
  }).fail(function(err) {
    if (err.status === 401) {
      return window.location.href = 'forge?page=forge_rule';
    } else {
      $('#info').text('Error fetching public key, unable to send user specific parameters securely');
      return $('#info').attr('class', 'error');
    }
  });

  fOnLoad = function() {
    var arrKV, arrParams, editor, fFetchActionFunctionParams, fFetchActionParams, fFetchEventParams, id, obj, param, _i, _len;
    document.title = 'Rule Forge!';
    $('#pagetitle').text('{{{user.username}}}, forge your ECA Rule!');
    editor = ace.edit("editor_conditions");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.setShowPrintMargin(false);
    fFetchEventParams = function(name) {
      var arr, obj;
      if (name) {
        arr = name.split(' -> ');
        obj = {
          command: 'get_event_poller_params',
          payload: {
            id: arr[0]
          }
        };
        obj.payload = JSON.stringify(obj.payload);
        return $.post('/usercommand', obj).done(function(data) {
          var fAppendParam, oParams, shielded, table, _results;
          if (data.message) {
            oParams = JSON.parse(data.message);
            $('#event_poller_params table').remove();
            table = $('<table>');
            $('#event_poller_params').append(table);
            fAppendParam = function(name, shielded) {
              var inp, tr;
              tr = $('<tr>');
              tr.append($('<td>').css('width', '20px'));
              tr.append($('<td>').attr('class', 'key').text(name));
              inp = $('<input>').attr('id', "" + name);
              if (shielded) {
                inp.attr('type', 'password');
              }
              tr.append($('<td>').text(' : ').append(inp));
              return table.append(tr);
            };
            _results = [];
            for (name in oParams) {
              shielded = oParams[name];
              _results.push(fAppendParam(name, shielded));
            }
            return _results;
          }
        }).fail(fFailedRequest('Error fetching event poller params'));
      }
    };
    $.post('/usercommand', {
      command: 'get_event_pollers'
    }).done(function(data) {
      var err, events, fAppendEvents, id, oEps;
      try {
        oEps = JSON.parse(data.message);
      } catch (_error) {
        err = _error;
        console.error('ERROR: non-object received from server: ' + data.message);
        return;
      }
      fAppendEvents = function(id, events) {
        var evt, fAppendEvent, _i, _len, _results;
        fAppendEvent = function(evt) {
          return $('#select_event').append($('<option>').text(id + ' -> ' + evt));
        };
        _results = [];
        for (_i = 0, _len = events.length; _i < _len; _i++) {
          evt = events[_i];
          _results.push(fAppendEvent(evt));
        }
        return _results;
      };
      for (id in oEps) {
        events = oEps[id];
        fAppendEvents(id, events);
      }
      return fFetchEventParams($('#select_event option:selected').text());
    }).fail(fFailedRequest('Error fetching event poller'));
    $('#select_event').change(function() {
      return fFetchEventParams($(this).val());
    });
    obj = {
      command: 'get_action_invokers'
    };
    $.post('/usercommand', obj).done(function(data) {
      var actions, err, fAppendActions, module, oAis, _results;
      try {
        oAis = JSON.parse(data.message);
      } catch (_error) {
        err = _error;
        console.error('ERROR: non-object received from server: ' + data.message);
        return;
      }
      fAppendActions = function(module, actions) {
        var act, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = actions.length; _i < _len; _i++) {
          act = actions[_i];
          _results.push($('#select_actions').append($('<option>').text(module + ' -> ' + act)));
        }
        return _results;
      };
      _results = [];
      for (module in oAis) {
        actions = oAis[module];
        _results.push(fAppendActions(module, actions));
      }
      return _results;
    }).fail(fFailedRequest('Error fetching event poller'));
    fFetchActionParams = function(div, modName) {
      obj = {
        command: 'get_action_invoker_params',
        payload: {
          id: modName
        }
      };
      obj.payload = JSON.stringify(obj.payload);
      return $.post('/usercommand', obj).done(function(data) {
        var fAppendActionParam, name, oParams, sh, table, _results;
        if (data.message) {
          oParams = JSON.parse(data.message);
          table = $('<table>');
          div.append(table);
          fAppendActionParam = function(name, shielded) {
            var inp, tr;
            tr = $('<tr>');
            tr.append($('<td>').css('width', '20px'));
            tr.append($('<td>').attr('class', 'key').text(name));
            inp = $('<input>').attr('id', "" + name);
            if (shielded) {
              inp.attr('type', 'password');
            } else {
              inp.attr('type', 'text');
            }
            tr.append($('<td>').text(' : ').append(inp));
            return table.append(tr);
          };
          _results = [];
          for (name in oParams) {
            sh = oParams[name];
            _results.push(fAppendActionParam(name, sh));
          }
          return _results;
        }
      }).fail(fFailedRequest('Error fetching action invoker params'));
    };
    fFetchActionFunctionParams = function(tag, arrName) {
      obj = {
        command: 'get_action_invoker_function_params',
        payload: {
          id: arrName[0]
        }
      };
      obj.payload = JSON.stringify(obj.payload);
      return $.post('/usercommand', obj).done(function(data) {
        var functionArgument, oParams, table, td, tr, _i, _len, _ref, _results;
        if (data.message) {
          oParams = JSON.parse(data.message);
          if (oParams[arrName[1]]) {
            table = $('<table>').appendTo(tag);
            _ref = oParams[arrName[1]];
            _results = [];
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              functionArgument = _ref[_i];
              tr = $('<tr>').appendTo(table);
              td = $('<td>').appendTo(tr);
              td.append($('<div>').text(functionArgument));
              tr.append(td);
              td = $('<td>').appendTo(tr);
              td.append($('<input>').attr('type', 'text'));
              tr.append(td);
              tr.append(td);
              td = $('<td>').appendTo(tr);
              _results.push(td.append($('<input>').attr('type', 'checkbox')).attr('title', 'js-select expression to be resolved on event?'));
            }
            return _results;
          }
        }
      }).fail(fFailedRequest('Error fetching action invoker function params'));
    };
    $('#select_actions').on('change', function() {
      var arrEls, arrName, div, img, opt, subdiv, table, td, tr, _ref;
      opt = $('option:selected', this);
      arrName = opt.text().split(' -> ');
      arrEls = $("#action_params div.modName").map(function() {
        return $(this).text();
      }).get();
      table = $('#selected_actions');
      tr = $('<tr>').appendTo(table);
      img = $('<img>').attr('src', 'red_cross_small.png');
      tr.append($('<td>').css('width', '20px').append(img));
      tr.append($('<td>').attr('class', 'title').text(opt.val()));
      td = $('<td>').attr('class', 'funcMappings').appendTo(tr);
      fFetchActionFunctionParams(td, arrName);
      if (_ref = arrName[0], __indexOf.call(arrEls, _ref) < 0) {
        div = $('<div>').appendTo($('#action_params'));
        subdiv = $('<div> ').appendTo(div);
        subdiv.append($('<div>')).attr('class', 'modName underlined').text(arrName[0]);
        fFetchActionParams(div, arrName[0]);
      }
      return opt.remove();
    });
    $('#selected_actions').on('click', 'img', function() {
      var act, arrName, nMods, opt;
      act = $(this).closest('td').siblings('.title').text();
      arrName = act.split(' -> ');
      nMods = 0;
      $("#selected_actions td.title").each(function() {
        var arrNm;
        arrNm = $(this).text().split(' -> ');
        if (arrNm[0] === arrName[0]) {
          return nMods++;
        }
      });
      if (nMods === 1) {
        $('#action_params > div').each(function() {
          if ($(this).children('div.modName').text() === arrName[0]) {
            return $(this).remove();
          }
        });
      }
      opt = $('<option>').text(arrName[0]);
      $('#select_actions').append(opt);
      return $(this).closest('tr').remove();
    });
    $('#but_submit').click(function() {
      var actParams, acts, ap, conds, encryptedParams, ep, err;
      try {
        if ($('#select_event option:selected').length === 0) {
          throw new Error('Please create an Event Poller first!');
        }
        if ($('#input_id').val() === '') {
          throw new Error('Please enter a rule name!');
        }
        ep = {};
        $("#event_poller_params tr").each(function() {
          var name, val;
          val = $('input', this).val();
          name = $(this).children('.key').text();
          if (val === '') {
            throw new Error("Please enter a value for '" + name + "' in the event module!");
          }
          return ep[name] = val;
        });
        if ($('#selected_actions tr').length === 0) {
          throw new Error('Please select at least one action or create one!');
        }
        ap = {};
        $('> div', $('#action_params')).each(function() {
          var encryptedParams, modName, params;
          modName = $('.modName', this).text();
          params = {};
          $('tr', this).each(function() {
            var key, val;
            key = $('.key', this).text();
            val = $('input', this).val();
            if (val === '') {
              throw new Error("'" + key + "' missing for '" + modName + "'");
            }
            return params[key] = val;
          });
          encryptedParams = cryptico.encrypt(JSON.stringify(params), strPublicKey);
          return ap[modName] = encryptedParams.cipher;
        });
        acts = [];
        actParams = {};
        $('#selected_actions').each(function() {
          acts.push($('.title', this).text());
          return $('.funcMappings tr').each(function() {
            console.log($('input[type=text]', this).val());
            return console.log($('input[type=checkbox]', this).is(':checked'));
          });
        });
        try {
          conds = JSON.parse(editor.getValue());
        } catch (_error) {
          err = _error;
          throw new Error("Parsing of your conditions failed! Needs to be an Array of Strings!");
        }
        if (!(conds instanceof Array)) {
          throw new Error("Conditions Invalid! Needs to be an Array of Strings!");
        }
        encryptedParams = cryptico.encrypt(JSON.stringify(ep), strPublicKey);
        obj = {
          command: 'forge_rule',
          payload: {
            id: $('#input_id').val(),
            event: $('#select_event option:selected').val(),
            event_params: encryptedParams.cipher,
            conditions: conds,
            actions: acts,
            action_params: ap,
            action_functions: actParams
          }
        };
        obj.payload = JSON.stringify(obj.payload);
        window.scrollTo(0, 0);
        return $.post('/usercommand', obj).done(function(data) {
          $('#info').text(data.message);
          return $('#info').attr('class', 'success');
        }).fail(function(err) {
          var msg;
          if (err.responseText === '') {
            msg = 'No Response from Server!';
          } else {
            try {
              msg = JSON.parse(err.responseText).message;
            } catch (_error) {}
          }
          return fFailedRequest('Error in upload: ' + msg)(err);
        });
      } catch (_error) {
        err = _error;
        $('#info').text('Error in upload: ' + err.message);
        $('#info').attr('class', 'error');
        return alert(err.message);
      }
    });
    arrParams = window.location.search.substring(1).split('&');
    id = '';
    for (_i = 0, _len = arrParams.length; _i < _len; _i++) {
      param = arrParams[_i];
      arrKV = param.split('=');
      if (arrKV[0] === 'id') {
        id = decodeURIComponent(arrKV[1]);
      }
    }
    if (id !== '') {
      return console.log(id);
    }
  };

  window.addEventListener('load', fOnLoad, true);

}).call(this);
