// Generated by CoffeeScript 1.7.1
(function() {
  var arrKV, arrParams, fFailedRequest, fOnLoad, fPlaceAndPaintInterval, oParams, param, strPublicKey, _i, _len,
    __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; };

  arrParams = window.location.search.substring(1).split('&');

  oParams = {};

  for (_i = 0, _len = arrParams.length; _i < _len; _i++) {
    param = arrParams[_i];
    arrKV = param.split('=');
    oParams[arrKV[0]] = arrKV[1];
  }

  if (oParams.id) {
    oParams.id = decodeURIComponent(oParams.id);
  }

  strPublicKey = '';

  fPlaceAndPaintInterval = function() {
    return $('#input_interval').html('Interval: <input id="event_interval" type="text" /> <b>"days hours:minutes"</b>, default = 10 minutes');
  };

  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 editor, fAddActionUserArgs, fAddActionUserParams, fAddEventParams, fAddEventUserArgs, fAddSelectedAction, fFetchActionFunctionArgs, fFetchActionParams, fFetchEventFunctionArgs, fFetchEventParams, fFillActionFunction, fFillEventParams, obj;
    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);
    $.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, _j, _len1, _results;
        fAppendEvent = function(evt) {
          return $('#select_event').append($('<option>').text(id + ' -> ' + evt));
        };
        _results = [];
        for (_j = 0, _len1 = events.length; _j < _len1; _j++) {
          evt = events[_j];
          _results.push(fAppendEvent(evt));
        }
        return _results;
      };
      for (id in oEps) {
        events = oEps[id];
        fAppendEvents(id, events);
      }
      $('#input_event').val($('#select_event').val());
      return fFetchEventParams($('#select_event option:selected').text());
    }).fail(fFailedRequest('Error fetching event poller'));
    $('#select_event').change(function() {
      var evtFunc;
      evtFunc = $(this).val();
      if (evtFunc === '') {
        $('#input_interval').html('');
      } else {
        fPlaceAndPaintInterval();
      }
      $('#input_event').val(evtFunc);
      return fFetchEventParams(evtFunc);
    });
    $('#input_event').change(function() {
      $('#select_event').val('');
      $('#select_event').val($(this).val());
      fFetchEventParams($('#select_event').val());
      if ($('#select_event').val() === '') {
        return $('#input_interval').html('');
      } else {
        return fPlaceAndPaintInterval();
      }
    });
    fFetchEventParams = function(name) {
      var arr, obj;
      $('#event_poller_params *').remove();
      if (name) {
        arr = name.split(' -> ');
        obj = {
          command: 'get_event_poller_params',
          payload: JSON.stringify({
            id: arr[0]
          })
        };
        $.post('/usercommand', obj).done(fAddEventParams(arr[0])).fail(fFailedRequest('Error fetching event poller params'));
        return fFetchEventFunctionArgs(arr);
      }
    };
    fFetchEventFunctionArgs = function(arrName) {
      var obj;
      obj = {
        command: 'get_event_poller_function_arguments',
        payload: JSON.stringify({
          id: arrName[0]
        })
      };
      return $.post('/usercommand', obj).done(function(data) {
        var functionArgument, table, td, tr, _j, _len1, _ref, _results;
        if (data.message) {
          oParams = JSON.parse(data.message);
          if (oParams[arrName[1]]) {
            if (oParams[arrName[1]].length > 0) {
              $('#event_poller_params').append($("<b>").text('Required Function Parameters:'));
            }
            table = $('<table>').appendTo($('#event_poller_params'));
            _ref = oParams[arrName[1]];
            _results = [];
            for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
              functionArgument = _ref[_j];
              tr = $('<tr>').attr('class', 'funcMappings').appendTo(table);
              tr.append($('<td>').css('width', '20px'));
              td = $('<td>').appendTo(tr);
              td.append($('<div>').attr('class', 'funcarg').text(functionArgument));
              tr.append(td);
              tr.append($('<td>').text(' : '));
              td = $('<td>').appendTo(tr);
              td.append($('<input>').attr('type', 'text'));
              _results.push(tr.append(td));
            }
            return _results;
          }
        }
      }).fail(fFailedRequest('Error fetching action invoker function params'));
    };
    fAddEventParams = function(id) {
      return function(data) {
        var fAppendParam, i, name, shielded, table;
        if (data.message) {
          oParams = JSON.parse(data.message);
          table = $('<table>');
          i = 0;
          fAppendParam = function(name, shielded) {
            var inp, tr;
            i++;
            tr = $('<tr>');
            tr.append($('<td>').css('width', '20px'));
            tr.append($('<td>').attr('class', 'key').text(name));
            inp = $('<input>');
            if (shielded) {
              inp.attr('type', 'password');
            }
            tr.append($('<td>').text(' : ').append(inp));
            return table.append(tr);
          };
          for (name in oParams) {
            shielded = oParams[name];
            fAppendParam(name, shielded);
          }
          if (i > 0) {
            $('#event_poller_params').html('<b>Required Global Parameters:</b>');
            $('#event_poller_params').append(table);
          }
          return fFillEventParams(id);
        }
      };
    };
    fFillEventParams = function(moduleId) {
      var obj;
      obj = {
        command: 'get_event_poller_user_params',
        payload: JSON.stringify({
          id: moduleId
        })
      };
      $.post('/usercommand', obj).done(function(data) {
        var oParam, par, _results;
        oParams = JSON.parse(data.message);
        _results = [];
        for (param in oParams) {
          oParam = oParams[param];
          par = $("#event_poller_params tr").filter(function() {
            return $('td.key', this).text() === param;
          });
          $('input', par).val(oParam.value);
          $('input', par).attr('unchanged', 'true');
          _results.push($('input', par).change(function() {
            return $(this).attr('unchanged', 'false');
          }));
        }
        return _results;
      });
      obj.command = 'get_event_poller_user_arguments';
      obj.payload = JSON.stringify({
        ruleId: $('#input_id').val(),
        moduleId: moduleId
      });
      return $.post('/usercommand', obj).done(fAddEventUserArgs(moduleId));
    };
    fAddEventUserArgs = function(name) {
      return function(data) {
        var arrFuncs, key, oFunc, par, tr, _ref, _results;
        _ref = data.message;
        _results = [];
        for (key in _ref) {
          arrFuncs = _ref[key];
          par = $("#event_poller_params");
          _results.push((function() {
            var _j, _len1, _ref1, _results1;
            _ref1 = JSON.parse(arrFuncs);
            _results1 = [];
            for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
              oFunc = _ref1[_j];
              tr = $("tr", par).filter(function() {
                return $('.funcarg', this).text() === ("" + oFunc.argument);
              });
              $("input[type=text]", tr).val(oFunc.value);
              _results1.push($("input[type=checkbox]", tr).prop('checked', oFunc.jsselector));
            }
            return _results1;
          })());
        }
        return _results;
      };
    };
    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, arrEls, _j, _len1, _results;
        _results = [];
        for (_j = 0, _len1 = actions.length; _j < _len1; _j++) {
          act = actions[_j];
          arrEls = $("#action_params div").filter(function() {
            return $(this).text() === ("" + module + " -> " + act);
          });
          if (arrEls.length === 0) {
            _results.push($('#select_actions').append($('<option>').text(module + ' -> ' + act)));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };
      _results = [];
      for (module in oAis) {
        actions = oAis[module];
        _results.push(fAppendActions(module, actions));
      }
      return _results;
    }).fail(fFailedRequest('Error fetching event poller'));
    fAddSelectedAction = function(name) {
      var arrEls, arrName, div, img, subdiv, table, td, tr, _ref;
      arrName = name.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(name));
      td = $('<td>').attr('class', 'funcMappings').appendTo(tr);
      fFetchActionFunctionArgs(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]);
      }
      $("#select_actions option").each(function() {
        if ($(this).text() === name) {
          return $(this).remove();
        }
      });
      return fFillActionFunction(arrName[0]);
    };
    fFetchActionParams = function(div, modName) {
      obj = {
        command: 'get_action_invoker_params',
        payload: JSON.stringify({
          id: modName
        })
      };
      return $.post('/usercommand', obj).done(function(data) {
        var fAppendActionParam, name, 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>');
            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'));
    };
    fFetchActionFunctionArgs = function(tag, arrName) {
      obj = {
        command: 'get_action_invoker_function_arguments',
        payload: JSON.stringify({
          id: arrName[0]
        })
      };
      return $.post('/usercommand', obj).done(function(data) {
        var functionArgument, table, td, tr, _j, _len1, _ref, _results;
        if (data.message) {
          oParams = JSON.parse(data.message);
          if (oParams[arrName[1]]) {
            table = $('<table>').appendTo(tag);
            _ref = oParams[arrName[1]];
            _results = [];
            for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
              functionArgument = _ref[_j];
              tr = $('<tr>').appendTo(table);
              td = $('<td>').appendTo(tr);
              td.append($('<div>').attr('class', 'funcarg').text(functionArgument));
              tr.append(td);
              td = $('<td>').appendTo(tr);
              td.append($('<input>').attr('type', 'text'));
              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'));
    };
    fFillActionFunction = function(name) {
      obj = {
        command: 'get_action_invoker_user_params',
        payload: JSON.stringify({
          id: name
        })
      };
      $.post('/usercommand', obj).done(fAddActionUserParams(name));
      obj.command = 'get_action_invoker_user_arguments';
      obj.payload = JSON.stringify({
        ruleId: $('#input_id').val(),
        moduleId: name
      });
      return $.post('/usercommand', obj).done(fAddActionUserArgs(name));
    };
    fAddActionUserParams = function(name) {
      return function(data) {
        var domMod, oParam, par, _results;
        oParams = JSON.parse(data.message);
        domMod = $("#action_params div").filter(function() {
          return $('div.modName', this).text() === name;
        });
        _results = [];
        for (param in oParams) {
          oParam = oParams[param];
          par = $("tr", domMod).filter(function() {
            return $('td.key', this).text() === param;
          });
          $('input', par).val(oParam.value);
          $('input', par).attr('unchanged', 'true');
          _results.push($('input', par).change(function() {
            return $(this).attr('unchanged', 'false');
          }));
        }
        return _results;
      };
    };
    fAddActionUserArgs = function(name) {
      return function(data) {
        var arrFuncs, key, oFunc, par, tr, _ref, _results;
        _ref = data.message;
        _results = [];
        for (key in _ref) {
          arrFuncs = _ref[key];
          par = $("#selected_actions tr").filter(function() {
            return $('td.title', this).text() === ("" + name + " -> " + key);
          });
          _results.push((function() {
            var _j, _len1, _ref1, _results1;
            _ref1 = JSON.parse(arrFuncs);
            _results1 = [];
            for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
              oFunc = _ref1[_j];
              tr = $("tr", par).filter(function() {
                return $('.funcarg', this).text() === ("" + oFunc.argument);
              });
              $("input[type=text]", tr).val(oFunc.value);
              _results1.push($("input[type=checkbox]", tr).prop('checked', oFunc.jsselector));
            }
            return _results1;
          })());
        }
        return _results;
      };
    };
    $('#select_actions').on('change', function() {
      var opt;
      opt = $('option:selected', this);
      return fAddSelectedAction(opt.text());
    });
    $('#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(act);
      $('#select_actions').append(opt);
      return $(this).closest('tr').remove();
    });
    $('#but_submit').click(function() {
      var actFuncs, acts, ap, arrInp, conds, d, ep, err, eventId, evtFuncs, fCheckOverwrite, fParseTime, mins, txtInterval;
      window.scrollTo(0, 0);
      $('#info').text('');
      try {
        if ($('#input_id').val() === '') {
          $('#input_id').focus();
          throw new Error('Please enter a rule name!');
        }
        eventId = $('#input_event').val();
        if (eventId === '') {
          $('#input_event').focus();
          throw new Error('Please assign an event!');
        }
        ep = {};
        $("#event_poller_params tr").each(function() {
          var encryptedParam, key, shielded, val;
          key = $(this).children('.key').text();
          val = $('input', this).val();
          if (val === '') {
            $('input', this).focus();
            throw new Error("Please enter a value for '" + key + "' in the event module!");
          }
          shielded = $('input', this).attr('type') === 'password';
          ep[key] = {
            shielded: shielded
          };
          if (!shielded || $('input', this).attr('unchanged') !== 'true') {
            encryptedParam = cryptico.encrypt(val, strPublicKey);
            return ep[key].value = encryptedParam.cipher;
          } else {
            return ep[key].value = val;
          }
        });
        evtFuncs = {};
        evtFuncs[eventId] = [];
        $('#event_poller_params tr.funcMappings').each(function() {
          return evtFuncs[eventId].push({
            argument: $('div.funcarg', this).text(),
            value: $('input[type=text]', this).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 modName, params;
          modName = $('.modName', this).text();
          params = {};
          $('tr', this).each(function() {
            var encryptedParam, key, shielded, val;
            key = $('.key', this).text();
            val = $('input', this).val();
            shielded = $('input', this).attr('type') === 'password';
            if (val === '') {
              $('input', this).focus();
              throw new Error("'" + key + "' missing for '" + modName + "'");
            }
            params[key] = {
              shielded: shielded
            };
            if (!shielded || $('input', this).attr('unchanged') !== 'true') {
              encryptedParam = cryptico.encrypt(val, strPublicKey);
              return params[key].value = encryptedParam.cipher;
            } else {
              return params[key].value = val;
            }
          });
          return ap[modName] = params;
        });
        acts = [];
        actFuncs = {};
        $('#selected_actions td.title').each(function() {
          var actionName, par;
          actionName = $(this).text();
          actFuncs[actionName] = [];
          acts.push(actionName);
          par = $(this).parent();
          return $('.funcMappings tr', par).each(function() {
            return actFuncs[actionName].push({
              argument: $('div.funcarg', this).text(),
              value: $('input[type=text]', this).val(),
              jsselector: $('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!");
        }
        fParseTime = function(str, hasDay) {
          var arrTime, def, h, time;
          arrTime = str.split(':');
          if (hasDay) {
            def = 0;
          } else {
            def = 10;
          }
          if (arrTime.length === 1) {
            time = parseInt(str) || def;
            if (hasDay) {
              return time * 60;
            } else {
              return time;
            }
          } else {
            h = parseInt(arrTime[0]) || 0;
            if (h > 0) {
              def = 0;
            }
            return h * 60 + (parseInt(arrTime[1]) || def);
          }
        };
        txtInterval = $('#event_interval').val();
        if (!txtInterval) {
          mins = 10;
        } else {
          arrInp = txtInterval.split(' ');
          if (arrInp.length === 1) {
            mins = fParseTime(txtInterval);
          } else {
            d = parseInt(arrInp[0]) || 0;
            mins = d * 24 * 60 + fParseTime(arrInp[1], true);
          }
        }
        mins = Math.min(mins, 35700);
        mins = Math.max(1, mins);
        fCheckOverwrite = function(obj) {
          return function(err) {
            var payl;
            if (err.status === 409) {
              if (confirm('Are you sure you want to overwrite the existing rule?')) {
                payl = JSON.parse(obj.payload);
                payl.overwrite = true;
                obj.payload = JSON.stringify(payl);
                return $.post('/usercommand', obj).done(function(data) {
                  $('#info').text(data.message);
                  return $('#info').attr('class', 'success');
                }).fail(fFailedRequest("" + obj.id + " not stored!"));
              }
            } else {
              return fFailedRequest("" + obj.id + " not stored!")(err);
            }
          };
        };
        obj = {
          command: 'forge_rule',
          payload: JSON.stringify({
            id: $('#input_id').val(),
            event: eventId,
            event_params: ep,
            event_interval: mins,
            event_functions: evtFuncs,
            conditions: conds,
            actions: acts,
            action_params: ap,
            action_functions: actFuncs
          })
        };
        return $.post('/usercommand', obj).done(function(data) {
          $('#info').text(data.message);
          return $('#info').attr('class', 'success');
        }).fail(fCheckOverwrite(obj));
      } catch (_error) {
        err = _error;
        console.log(err);
        $('#info').text('Error in upload: ' + err.message);
        $('#info').attr('class', 'error');
        alert(err.message);
        throw err;
      }
    });
    if (oParams.id) {
      obj = {
        command: 'get_rule',
        payload: JSON.stringify({
          id: oParams.id
        })
      };
      return $.post('/usercommand', obj).done(function(data) {
        var action, arrName, oRule, _j, _len1, _ref, _results;
        oRule = JSON.parse(data.message);
        if (oRule) {
          $('#input_id').val(oRule.id);
          $('#select_event').val(oRule.event);
          if ($('#select_event').val() !== '') {
            fFetchEventParams(oRule.event);
            fPlaceAndPaintInterval();
          }
          $('#input_event').val(oRule.event);
          $('#event_interval').val(oRule.event_interval);
          editor.setValue(JSON.stringify(oRule.conditions, void 0, 2));
          _ref = oRule.actions;
          _results = [];
          for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
            action = _ref[_j];
            arrName = action.split(' -> ');
            _results.push(fAddSelectedAction(action));
          }
          return _results;
        }
      }).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);
      });
    }
  };

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

}).call(this);
