// Generated by CoffeeScript 1.10.0
var Model, model,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

model = null;

$(function() {
  var dropZone;
  model = new Model();
  ko.applyBindings(model);
  dropZone = document.getElementById('drop-zone');
  dropZone.addEventListener('dragenter', model.stopPropagation);
  dropZone.addEventListener('dragover', model.stopPropagation);
  return dropZone.addEventListener('drop', model.processDrop);
});

Model = (function() {
  function Model() {
    this.inStock = bind(this.inStock, this);
    this.processDrop = bind(this.processDrop, this);
  }

  Model.prototype.racks = ko.observableArray();

  Model.prototype.cat = '';

  Model.prototype.stopPropagation = function(e) {
    e.stopPropagation();
    return e.preventDefault();
  };

  Model.prototype.processDrop = function(e) {
    var file, reader;
    this.stopPropagation(e);
    file = e.dataTransfer.files[0];
    if (file.name.match(/^Sd{4}.*.csv$/i)) {
      $('#fileInfo').text(file.name);
      this.cat = file.name.substring(0, 5).toUpperCase();
      reader = new FileReader();
      reader.onload = (function(_this) {
        return function() {
          var hasNoRead, i, j, len, len1, plate, plateRow, rack, ref;
          rack = new CodeLibRack();
          rack.loadFromCsv(reader.result);
          _this.racks.removeAll();
          _this.racks.push(rack);
          hasNoRead = false;
          ref = rack.plates;
          for (i = 0, len = ref.length; i < len; i++) {
            plateRow = ref[i];
            for (j = 0, len1 = plateRow.length; j < len1; j++) {
              plate = plateRow[j];
              if ('No Read' === plate.code) {
                hasNoRead = true;
              }
            }
          }
          return $('#inStockButton').prop('disabled', hasNoRead);
        };
      })(this);
      return reader.readAsText(file);
    } else {
      $('#fileInfo').text('invalid file');
      $('#inStockButton').prop('disabled', true);
      return this.racks.removeAll();
    }
  };

  Model.prototype.inStock = function() {
    var codes, i, j, len, len1, plate, plateRow, racks, ref;
    codes = [];
    racks = ko.mapping.toJS(this.racks);
    if (racks.length) {
      ref = racks[0].plates;
      for (i = 0, len = ref.length; i < len; i++) {
        plateRow = ref[i];
        for (j = 0, len1 = plateRow.length; j < len1; j++) {
          plate = plateRow[j];
          if (plate.code.match(/^d+$/)) {
            codes.push(plate.code);
          }
        }
      }
      return $.postJSON('doInStock.jhtml', {
        cat: this.cat,
        codes: codes
      }).done((function(_this) {
        return function(json) {
          if (json.error) {
            return alert(json.error);
          } else {
            return alert('上传成功');
          }
        };
      })(this));
    }
  };

  return Model;

})();