// Generated by CoffeeScript 1.3.3
(function() {
  var $AL,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  $AL = window.$AL;

  $AL.LayoutView = (function(_super) {

    __extends(LayoutView, _super);

    function LayoutView() {
      return LayoutView.__super__.constructor.apply(this, arguments);
    }

    LayoutView.prototype.render = function() {
      this.$el.html(_.template($('#layout-template').html(), {}));
      return this;
    };

    return LayoutView;

  })(Backbone.View);

  $AL.TerminalView = (function(_super) {

    __extends(TerminalView, _super);

    function TerminalView() {
      return TerminalView.__super__.constructor.apply(this, arguments);
    }

    TerminalView.prototype.events = {
      "click a#terminalCloseBtn": "close"
    };

    TerminalView.prototype.close = function() {
      $AL.main_tab_set.remove_tab(this.$el.attr('routeID'));
      $AL.main_tab_set.activate('cluster');
      return this;
    };

    TerminalView.prototype.render = function() {
      var ip, port, protocol, terminalURL;
      protocol = 'http://';
      ip = $('#terminalIP').val();
      port = $('#terminalPort').val();
      if ($('#terminalSSL:checked').length > 0) {
        protocol = 'https://';
      }
      terminalURL = protocol + ip + ':' + port;
      this.$el.prepend(_.template($('#terminal-template').html(), {
        'url': terminalURL
      }));
      return this;
    };

    return TerminalView;

  })(Backbone.View);

  $AL.ClusterView = (function(_super) {

    __extends(ClusterView, _super);

    function ClusterView() {
      return ClusterView.__super__.constructor.apply(this, arguments);
    }

    ClusterView.prototype.events = {
      "click a#saveMasterURL": "saveURL",
      "click a#connectTerminal": "connectTerminal"
    };

    ClusterView.prototype.connectTerminal = function() {
      var ip, port, routeID, terminalView;
      ip = $('#terminalIP').val();
      port = $('#terminalPort').val();
      if (ip.length > 0 && port.length > 0) {
        routeID = 'term' + ip + (new Date()).getTime();
        terminalView = new $AL.TerminalView;
        $AL.main_tab_set.add_tab({
          tab_name: ip,
          view: terminalView,
          route: routeID
        });
        terminalView.$el.attr('routeID', routeID);
        terminalView.render();
        $AL.main_tab_set.activate(routeID);
      }
      $('#terminalModal').modal('hide');
      return this;
    };

    ClusterView.prototype.saveURL = function() {
      var self, url;
      self = this;
      url = $("#newMasterURL").val();
      if (url.length > 0) {
        $.when($.get('/disco/updatemasterurl', {
          url: url
        })).then(function(urldata) {
          $("#urlModal").modal("hide");
          return self.render();
        });
      } else {
        $("#urlModal").modal("hide");
      }
      return this;
    };

    ClusterView.prototype.render = function() {
      var self;
      self = this;
      this.$el.empty().prepend(_.template($('#cluster-template').html(), {}));
      self.nodeCount = 0;
      $.when($.get('/disco/summary')).then(function(discodata) {
        $("#clusterMasterURL").append(discodata.url);
        $("#discoBtn").attr("href", discodata.url);
        $("#clusterNumNodes").append(discodata.numNodes);
        self.nodeCount = discodata.numNodes;
        return $("#newMasterURL").attr("placeholder", discodata.url);
      });
      $.when($.get('/disco/nodeinfo')).then(function(discodata) {
        return $.each(discodata, function(key, value) {
          value.nodename = key;
          value.diskfree = (value.diskfree / 1048576).toFixed(1) + ' GB';
          value.diskused = (value.diskused / 1048576).toFixed(1) + ' GB';
          $('#clusterContent').append(_.template($('#cluster-nodeinfo-template').html(), value));
          if (self.nodeCount < 4) {
            $('.al-nodeinfo').removeClass('span3');
            $('.al-nodeinfo').addClass('span4');
          }
        });
      });
      $('#clusterMasterHelp').popover({
        title: 'Disco Master URL',
        content: this.clusterMasterHelpContent()
      });
      return this;
    };

    ClusterView.prototype.clusterMasterHelpContent = function() {
      return "This URL points to the Disco master node.  Click on it to edit the value.  The format is http://server:port";
    };

    return ClusterView;

  })(Backbone.View);

  $AL.ConfigView = (function(_super) {

    __extends(ConfigView, _super);

    function ConfigView() {
      return ConfigView.__super__.constructor.apply(this, arguments);
    }

    ConfigView.prototype.events = {
      "change #envSelect": "envChange",
      "click #envAdd": "envAdd"
    };

    ConfigView.prototype.envAdd = function() {
      console.log('envAdd');
      if ($AL.addEnvView === null) {
        console.log('creating new addEnvView');
        $AL.addEnvView = new $AL.AddEnvView();
        $AL.main_tab_set.add_tab({
          tab_name: 'Add',
          view: $AL.addEnvView,
          route: 'add'
        });
        $AL.addEnvView.render();
      }
      $AL.main_tab_set.activate('add');
      return window.$AL.resizeRoot();
    };

    ConfigView.prototype.envChange = function() {
      var optVal;
      console.log('envChange');
      optVal = $('#envSelect').val();
      if (optVal === 'Default') {
        $('#envDelete').addClass('disabled');
        $('#envDelete').unbind();
      } else {
        $('#envDelete').removeClass('disabled');
        $('#envDelete').click(this.envDelete);
      }
      return this.loadenv(optVal);
    };

    ConfigView.prototype.envDelete = function() {
      var optText, optVal;
      console.log('envDelete');
      optVal = $('#envSelect').val();
      optText = $('#envSelect option:selected').text();
      return $AL.dialog('Confirm Delete?', 'Delete <b>' + optText + '</b> environment?', function() {
        $AL.dialog.updateTitle('Deleting environment');
        $AL.dialog.removeFooter();
        $AL.dialog.showprogress();
        return $.when($.get('/deleteenv?name=' + optText)).then(function(data) {
          $AL.dialog.dismiss();
          if (data.errorcode === 0) {
            alert('Environment [' + optText + '] deleted.');
            return $.when($AL.configView.loadEnvList()).then(function(data) {
              return $AL.configView.loadenv('Default');
            });
          } else {
            return alert('There was a problem. Unable to delete the environment [' + optText + ']. ' + data.errormsg);
          }
        });
      }, function() {});
    };

    ConfigView.prototype.render = function() {
      this.$el.empty().prepend(_.template($('#config-template').html(), {}));
      this.loadEnvList();
      this.loadenv('Default');
      $('#envDelete').addClass('disabled');
      return this;
    };

    ConfigView.prototype.loadEnvList = function() {
      $.when($.get('/getenvlist')).then(function(data) {
        var optVal, optionTemplate;
        optionTemplate = _.template($('#config-option-template').html());
        if (data.errorcode === 0) {
          $('#envSelect').empty();
          $.each(data.envlist, function(index, ele) {
            return $('#envSelect').append(optionTemplate({
              'val': ele,
              'ele': ele
            }));
          });
          optVal = $('#envSelect').val();
          if (optVal === 'Default') {
            $('#envDelete').addClass('disabled');
            return $('#envDelete').unbind();
          }
        }
      });
      return this;
    };

    ConfigView.prototype.loadenv = function(envID) {
      if (envID.length === 0) {
        envID = $('#envSelect').val();
      }
      return $.when($.get('/getenv?id=' + envID)).then(function(data) {
        var rowTemplate, tableEle;
        $('#configDefaultPath').empty().prepend(data.path);
        tableEle = _.template($('#config-package-table').html(), {});
        $('#tableDiv').empty().append(tableEle);
        rowTemplate = _.template($('#config-package-row').html());
        if (data.errorcode === 0) {
          return $.each(data.packagelist, function(index, ele) {
            return $('#configTable').append(rowTemplate(ele));
          });
        } else {
          return $('#configTable').append(rowTemplate({
            'p': data.errormsg,
            'v': ''
          }));
        }
      });
    };

    return ConfigView;

  })(Backbone.View);

  $AL.AddEnvView = (function(_super) {
    var mouseOverList, mouseOverPid, mouseOverTimer, pyRequiredPackagesList;

    __extends(AddEnvView, _super);

    function AddEnvView() {
      return AddEnvView.__super__.constructor.apply(this, arguments);
    }

    mouseOverTimer = null;

    mouseOverPid = null;

    mouseOverList = null;

    pyRequiredPackagesList = [];

    AddEnvView.prototype.events = {
      "click #addEnvCloseBtn": "closeView",
      "click #addEnvSaveBtn": "saveEnv",
      "click #addEnvClearBtn": "clearPackages",
      "click #addEnvSelectBtn": "selectPackages",
      "change #addEnvPython": "updatePackages",
      "change #addEnvPackageCheckbox": "packageChecked",
      "mouseenter .al-package-link": "packageMouseEnter",
      "mouseleave .al-package-link": "packageMouseLeave"
    };

    AddEnvView.prototype.packageChecked = function(event) {
      var checked, pyVer, self, val;
      self = this;
      console.log(event.currentTarget.checked);
      console.log(event.currentTarget.name);
      console.log(event.currentTarget.defaultValue);
      checked = event.currentTarget.checked;
      console.log('checking dependencies...');
      val = event.currentTarget.defaultValue;
      val = val.replace(/,/g, '-');
      console.log(val);
      pyVer = $('#addEnvPython').val();
      if (checked) {
        $.when($.get('/packagedeps?package=' + val + '&pyver=' + pyVer)).then(function(data) {
          if (data.errorcode === 0) {
            return $.each(data.packages, function(index, packID) {
              var foundIt;
              foundIt = self.setcheckbox(packID, checked);
              if (!foundIt) {
                return alert('Did not find package: ' + packID);
              }
            });
          }
        });
      } else {

      }
    };

    AddEnvView.prototype.uncheckPackage = function(pID) {
      var pyVer, self;
      self = this;
      pyVer = $('#addEnvPython').val();
      console.log('uncheckPackage: ' + pID);
      $.when($.get('/packagedeps?package=' + pID + '&pyver=' + pyVer)).then(function(data) {
        if (data.errorcode === 0) {
          return $.each(data.packages, function(index, packID) {
            if (self.ischecked(packID)) {
              console.log('yes:' + packID);
              self.setcheckbox(packID, false);
              return self.uncheckPackage(packID.replace(/\|/g, '-'));
            }
          });
        }
      });
    };

    AddEnvView.prototype.ischecked = function(packID) {
      var retVal;
      retVal = false;
      packID = packID.replace(/\|/g, ',');
      $('input[name=package]').each(function() {
        if ($(this).val() === packID) {
          retVal = $(this).attr('checked');
          return false;
        }
      });
      return retVal;
    };

    AddEnvView.prototype.sethighlight = function(event, packID, checked) {
      var foundIt;
      packID = packID.replace(/\|/g, ',');
      foundIt = false;
      $('.al-package-link').each(function() {
        if (this.dataset.pid === packID) {
          foundIt = true;
          if (checked) {
            return $(this).addClass('al-package-highlight');
          } else {
            return $(this).removeClass('al-package-highlight');
          }
        }
      });
      return foundIt;
    };

    AddEnvView.prototype.setcheckbox = function(packID, checked) {
      var foundIt;
      packID = packID.replace(/\|/g, ',');
      foundIt = false;
      $('input[name=package]').each(function() {
        if ($(this).val() === packID) {
          foundIt = true;
          return $(this).attr('checked', checked);
        }
      });
      return foundIt;
    };

    AddEnvView.prototype.closeView = function() {
      $AL.main_tab_set.remove_tab('add');
      $AL.main_tab_set.activate('config');
      $AL.addEnvView = null;
    };

    AddEnvView.prototype.saveEnv = function() {
      var dialogBody, name, nameNotUnique, packageList, plist, pyVer, self;
      self = this;
      console.log('saveEnv');
      name = $('#addEnvName').val();
      if (name.length === 0) {
        alert('An environment name is required.');
        $('#addEnvName').focus();
        return false;
      }
      if (name.length < 4 || name.length > 32) {
        alert('The environment name must be more than 4 and less than 32 characters.');
        $('#addEnvName').focus();
        return false;
      }
      if (!/^[A-Za-z0-9]+$/.test(name)) {
        alert('The environment name may only contain letters and numbers');
        $('#addEnvName').focus();
        return false;
      }
      nameNotUnique = false;
      $.ajaxSetup({
        async: false
      });
      $.when($.get('/getenvlist')).then(function(data) {
        if (data.errorcode === 0) {
          return $.each(data.envlist, function(index, ele) {
            if (name === ele) {
              nameNotUnique = true;
              return false;
            }
          });
        }
      });
      $.ajaxSetup({
        async: true
      });
      if (nameNotUnique) {
        alert('The environment [' + name + '] already exists.');
        return false;
      }
      pyVer = $('#addEnvPython').val();
      if (pyVer.length === 0) {
        alert('Please select a Python version.');
        $('#addEnvPython').focus();
        return false;
      }
      packageList = [];
      $.each(pyRequiredPackagesList, function(index, packID) {
        return packageList.push(packID.replace(/\|/g, ','));
      });
      $('input[name=package]:checked').each(function() {
        return packageList.push($(this).val());
      });
      if (packageList.length === 0) {
        alert('At least one package must be selected.');
        return false;
      }
      dialogBody = '<p><b>Name:</b> ' + name + '</p>';
      dialogBody += '<p><b>Python Version:</b> ' + pyVer + '</p>';
      dialogBody += '<p><b>Packages:</b></p>';
      dialogBody += '<ul>';
      plist = [];
      $.each(packageList, function(index, packID) {
        var x;
        x = packID.split(',');
        dialogBody += '<li>' + x[0] + ', ' + x[1] + '</li>';
        return plist.push(packID.replace(/,/g, '-'));
      });
      dialogBody += '</ul>';
      $AL.dialog('Confirm Creation of New Environment', dialogBody, function() {
        $AL.dialog.updateTitle('Creating new environment');
        $AL.dialog.removeFooter();
        $AL.dialog.showprogress();
        return $.when($.post('/createenv', {
          'name': name,
          'pyver': pyVer,
          'plist[]': plist
        })).then(function(data) {
          if (data.errorcode === 0) {
            $AL.dialog.dismiss();
            alert('Environment [' + name + '] created.');
            $('#addEnvName').val('');
            self.clearPackages();
            return $AL.configView.loadEnvList();
          } else {
            return alert('There was a problem. Unable to create the new environment [' + name + ']. ' + data.errormsg);
          }
        });
      }, function() {});
    };

    AddEnvView.prototype.clearPackages = function() {
      console.log('clearPackages');
      $('input[name=package]').attr('checked', false);
    };

    AddEnvView.prototype.selectPackages = function() {
      console.log('selectPackages');
      $('input[name=package]').attr('checked', true);
    };

    AddEnvView.prototype.updatePackages = function() {
      var pyVer, self;
      self = this;
      pyVer = $('#addEnvPython').val();
      console.log(pyVer);
      if (pyVer.length > 0) {
        $.when($.get('/pythondeps?pyver=' + pyVer)).then(function(data) {
          var str;
          pyRequiredPackagesList = data.packages;
          if (data.errorcode === 0) {
            str = '';
            $.each(data.packages, function(index, ele) {
              var x;
              if (str.length > 0) {
                str = str + ', ';
              }
              x = ele.split('|');
              return str = str + x[0] + ' ' + x[1];
            });
            return $('#addEnvPackageDiv').empty().append(_.template($('#config-addenv-required-template').html(), {
              'title': 'REQUIRED PACKAGES',
              'str': str
            }));
          }
        });
        $.when($.get('/pythonrevdeps?pyver=' + pyVer)).then(function(data) {
          var cell1, cell2, cell3, cellCount, optDiv;
          if (data.errorcode === 0) {
            console.log(data);
            optDiv = _.template($('#config-addenv-optional-template').html(), {
              'title': 'OPTIONAL PACKAGES',
              'str': 'Check the packages you wish to include. Dependency packages will automatically be selected.<br>Hover over a package name to see dependencies.'
            });
            $('#addEnvPackageDiv').append(optDiv);
            cell1 = '';
            cell2 = '';
            cell3 = '';
            cellCount = 0;
            $.each(data.packages, function(index, ele) {
              var cellContent, x;
              cellCount++;
              x = ele.split('|');
              cellContent = _.template($('#config-addenv-cell-template').html(), {
                'package': x[0],
                'ver': x[1],
                'packID': x
              });
              if (cellCount === 1) {
                cell1 = cellContent;
                return true;
              } else if (cellCount === 2) {
                cell2 = cellContent;
                return true;
              } else if (cellCount === 3) {
                cell3 = cellContent;
              }
              $('#addEnvTable').append(_.template($('#config-addenv-tablerow-template').html(), {
                'cell1': cell1,
                'cell2': cell2,
                'cell3': cell3
              }));
              return cellCount = 0;
            });
            if (cellCount > 0 && cellCount < 3) {
              if (cellCount === 1) {
                cell2 = '';
                cell3 = '';
              } else if (cellCount === 2) {
                cell3 = '';
              }
              return $('#addEnvTable').append(_.template($('#config-addenv-tablerow-template').html(), {
                'cell1': cell1,
                'cell2': cell2,
                'cell3': cell3
              }));
            }
          }
        });
      } else {
        $('#addEnvPackageDiv').empty().prepend(_.template($('#p-template').html(), {
          'str': 'Select a Python version to cause the package list to be populated.'
        }));
      }
    };

    AddEnvView.prototype.packageMouseEnter = function(event) {
      var self;
      self = this;
      if (mouseOverTimer) {
        clearTimeout(mouseOverTimer);
        mouseOverTimer = null;
      } else {
        mouseOverPid = event.currentTarget.dataset.pid;
        mouseOverTimer = setTimeout(function() {
          var pyVer, val;
          val = mouseOverPid.replace(/,/g, '-');
          pyVer = $('#addEnvPython').val();
          $(event.currentTarget).addClass('al-package-highlight-bold');
          $.when($.get('/packagedeps?package=' + val + '&pyver=' + pyVer)).then(function(data) {
            if (data.errorcode === 0) {
              mouseOverList = data.packages;
              return $.each(data.packages, function(index, packID) {
                return self.sethighlight(event, packID, true);
              });
            }
          });
          clearTimeout(mouseOverTimer);
          return mouseOverTimer = null;
        }, 750);
      }
    };

    AddEnvView.prototype.packageMouseLeave = function(event) {
      var self;
      self = this;
      if (mouseOverTimer) {
        clearTimeout(mouseOverTimer);
      } else {
        $(event.currentTarget).removeClass('al-package-highlight-bold');
        $.each(mouseOverList, function(index, packID) {
          return self.sethighlight(event, packID, false);
        });
      }
      mouseOverPid = null;
      mouseOverList = null;
      mouseOverTimer = null;
    };

    AddEnvView.prototype.render = function() {
      if ($AL.version === 'CEt') {
        this.$el.empty().prepend(_.template($('#config-addenv-ce-template').html(), {
          'buyNowPage': $AL.anacondaBuyNowURL,
          'productPage': $AL.anacondaLearnMoreURL
        }));
      } else {
        this.$el.empty().prepend(_.template($('#config-addenv-pro-template').html(), {}));
        $('#addEnvNameHelp').popover({
          title: 'Environment Name',
          content: this.addEnvNameHelpContent()
        });
        $('#addEnvPythonHelp').popover({
          title: 'Python Version',
          content: this.addEnvPythonHelpContent()
        });
        $.when($.get('/pythonversions')).then(function(data) {
          var optionTemplate;
          optionTemplate = _.template($('#config-option-template').html());
          if (data.errorcode === 0) {
            return $.each(data.versions, function(index, ele) {
              return $('#addEnvPython').append(optionTemplate({
                'val': index,
                'ele': index
              }));
            });
          }
        });
        $('#addEnvName').focus();
      }
    };

    AddEnvView.prototype.addEnvNameHelpContent = function() {
      return 'The environment name can be 4-32 alphanumeric characters [A-z0-9] only.  No spaces or special characters.  The name must be unique within this Anaconda installation.';
    };

    AddEnvView.prototype.addEnvPythonHelpContent = function() {
      return 'Select the version of Python to be used in the environment.';
    };

    return AddEnvView;

  })(Backbone.View);

}).call(this);
