// Generated by CoffeeScript 1.7.1
(function() {
  var fOnLoad, strPublicKey;

  strPublicKey = '';

  $.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 {
      console.log(err);
      $('#info').text('Error fetching public key, unable to send user-specific parameters securely');
      return $('#info').attr('class', 'error');
    }
  });

  fOnLoad = function() {
    var arrActionInvoker, editor, fFetchActionParams, fFetchEventParams, obj;
    editor = ace.edit("editor_conditions");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.setShowPrintMargin(false);
    document.title = 'Rule Forge!';
    $('#pagetitle').text('{{{user.username}}}, forge your ECA Rule!');
    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 arrParams, fAppendParam, table, _i, _len, _results;
          if (data.message) {
            arrParams = JSON.parse(data.message);
            $('#event_poller_params table').remove();
            if (arrParams.length > 0) {
              table = $('<table>');
              $('#event_poller_params').append(table);
              fAppendParam = function(name) {
                var inp, tr;
                tr = $('<tr>');
                tr.append($('<td>').css('width', '20px'));
                tr.append($('<td>').attr('class', 'key').text(name));
                inp = $('<input>').attr('type', 'password').attr('id', "" + name);
                tr.append($('<td>').text(' :').append(inp));
                return table.append(tr);
              };
              _results = [];
              for (_i = 0, _len = arrParams.length; _i < _len; _i++) {
                name = arrParams[_i];
                _results.push(fAppendParam(name));
              }
              return _results;
            }
          }
        }).fail(function(err) {
          var fDelayed;
          if (err.status === 401) {
            return window.location.href = 'forge?page=forge_rule';
          } else {
            fDelayed = function() {
              console.log(err);
              $('#info').text('Error fetching event poller params');
              return $('#info').attr('class', 'error');
            };
            return setTimeout(fDelayed, 500);
          }
        });
      }
    };
    obj = {
      command: 'get_event_pollers'
    };
    $.post('/usercommand', obj).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(function(err) {
      var fDelayed;
      if (err.status === 401) {
        return window.location.href = 'forge?page=forge_rule';
      } else {
        fDelayed = function() {
          console.log(err);
          $('#info').text('Error fetching event poller');
          return $('#info').attr('class', 'error');
        };
        return setTimeout(fDelayed, 500);
      }
    });
    $('#select_event').change(function() {
      return fFetchEventParams($(this).val());
    });
    arrActionInvoker = [];
    obj = {
      command: 'get_action_invokers'
    };
    $.post('/usercommand', obj).done(function(data) {
      var actions, err, fAppendActions, i, id, oAis, _results;
      try {
        oAis = JSON.parse(data.message);
      } catch (_error) {
        err = _error;
        console.error('ERROR: non-object received from server: ' + data.message);
        return;
      }
      i = 0;
      fAppendActions = function(id, actions) {
        var act, fAppendAction, _i, _len, _results;
        fAppendAction = function(act) {
          $('#select_actions').append($('<option>').attr('id', i++).text(id + ' -> ' + act));
          return arrActionInvoker.push(id + ' -> ' + act);
        };
        _results = [];
        for (_i = 0, _len = actions.length; _i < _len; _i++) {
          act = actions[_i];
          _results.push(fAppendAction(act));
        }
        return _results;
      };
      _results = [];
      for (id in oAis) {
        actions = oAis[id];
        _results.push(fAppendActions(id, actions));
      }
      return _results;
    }).fail(function(err) {
      var fDelayed;
      if (err.status === 401) {
        return window.location.href = 'forge?page=forge_rule';
      } else {
        console.log(err);
        fDelayed = function() {
          $('#info').text('Error fetching event poller');
          return $('#info').attr('class', 'error');
        };
        return setTimeout(fDelayed, 500);
      }
    });
    fFetchActionParams = function(div, name) {
      obj = {
        command: 'get_action_invoker_params',
        payload: {
          id: name
        }
      };
      obj.payload = JSON.stringify(obj.payload);
      return $.post('/usercommand', obj).done(function(data) {
        var arrParams, fAppendActionParam, table, _i, _len, _results;
        if (data.message) {
          arrParams = JSON.parse(data.message);
          if (arrParams.length > 0) {
            table = $('<table>');
            div.append(table);
            fAppendActionParam = function(name) {
              var tr;
              tr = $('<tr>');
              tr.append($('<td>').css('width', '20px'));
              tr.append($('<td>').attr('class', 'key').text(name));
              tr.append($('<td>').text(' :').append($('<input>').attr('type', 'password')));
              return table.append(tr);
            };
            _results = [];
            for (_i = 0, _len = arrParams.length; _i < _len; _i++) {
              name = arrParams[_i];
              _results.push(fAppendActionParam(name));
            }
            return _results;
          }
        }
      }).fail(function(err) {
        var fDelayed;
        if (err.status === 401) {
          return window.location.href = 'forge?page=forge_rule';
        } else {
          console.log(err);
          fDelayed = function() {
            $('#info').text('Error fetching action invoker params');
            return $('#info').attr('class', 'error');
          };
          return setTimeout(fDelayed, 500);
        }
      });
    };
    $('#select_actions').on('change', function() {
      var arrAI, div, idAI, img, opt, table, td, tr;
      opt = $('option:selected', this);
      arrAI = opt.val().split(' -> ');
      idAI = opt.attr('id');
      table = $('#selected_actions');
      tr = $('<tr>').attr('id', 'title_' + idAI);
      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()));
      table.append(tr);
      if ($('#ap_' + idAI).length === 0) {
        div = $('<div>').attr('id', 'ap_' + idAI);
        td = $('<div> ');
        td.append($('<div>')).attr('class', 'modName underlined').text(arrAI[0]);
        div.append(td);
        $('#action_params').append(div);
        fFetchActionParams(div, arrAI[0]);
      }
      return opt.remove();
    });
    $('#selected_actions').on('click', 'img', function() {
      var arrName, id, name, opt;
      id = $(this).closest('tr').attr('id').substring(6);
      name = arrActionInvoker[id];
      arrName = name.split(' -> ');
      $('#title_' + id).remove();
      $('#params_' + id).remove();
      opt = $('<option>').attr('id', id).text(name);
      $('#select_actions').append(opt);
      return $('#ap_' + id).remove();
    });
    return $('#but_submit').click(function() {
      var 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, id, modName, params;
          modName = $('.modName', this).text();
          id = $(this).attr('id').substring(3);
          params = {};
          $('tr', this).each(function() {
            var key, val;
            key = $('.key', this).text();
            val = $('input', this).val();
            if (val === '') {
              throw new Error("'" + key + "' missing for '" + id + "'");
            }
            return params[key] = val;
          });
          encryptedParams = cryptico.encrypt(JSON.stringify(params), strPublicKey);
          return ap[modName] = encryptedParams.cipher;
        });
        acts = [];
        $('#selected_actions .title').each(function() {
          return acts.push($(this).text());
        });
        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
          }
        };
        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 fDelayed;
          if (err.status === 401) {
            return window.location.href = 'forge?page=forge_rule';
          } else {
            fDelayed = function() {
              var msg, oErr;
              if (err.responseText === '') {
                msg = 'No Response from Server!';
              } else {
                try {
                  oErr = JSON.parse(err.responseText);
                  msg = oErr.message;
                } catch (_error) {}
              }
              $('#info').text('Error in upload: ' + msg);
              return $('#info').attr('class', 'error');
            };
            return setTimeout(fDelayed, 500);
          }
        });
      } catch (_error) {
        err = _error;
        $('#info').text('Error in upload: ' + err.message);
        $('#info').attr('class', 'error');
        return alert(err.message);
      }
    });
  };

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

}).call(this);
