var CONFIG = CONFIG || {};
CONFIG.COL_NUM = 4; // 列数

/**
 * サポート情報印刷ビュー
 * 
 * @param arg
 * @constructor
 */
var SupportView = function SupportView(arg) {
  this.$el = arg.$el;
  this.template = arg.template;
  this.compiled = _.template(this.template);
};

SupportView.prototype.render = function render(data) {
  var tableData = [], begin, end;

  // 既定の列数ごとのデータを作成
  for (var i = 0, l = data.columns.length / CONFIG.COL_NUM; i < l; i++) {
    begin = i * CONFIG.COL_NUM;
    end = begin + CONFIG.COL_NUM;

    tableData.push({
      rows: data.rows,
      columns: data.columns.slice(begin, end)
    });
  }

  this.$el.html(this.compiled({data: tableData}));
};

/**
 * サポート一覧印刷画面
 *
 * @param arg
 * @constructor
 */
var App = function App(arg) {
  this.supportView = arg.supportView;
  this.supportModel = null;
};

App.prototype.initialize = function initialize() {
  var supportData, modelData, condition;

  // 選択したモデルで絞り込み
  // supportData = DB.get('support') || {};
  supportData = DB.bulk_get();
  modelData = _.get(supportData, 'search.models.' + _.get(supportData, 'search.tab', ''), []);
  data.columns = filterModelData(data.columns, modelData);
  this.supportModel = new SupportModel({data:data});

  // 検索条件を読み込み
  condition = this.loadCondition();

  this.supportView.render(this.supportModel.find(condition));
};

/**
 * 検索条件を読み込み
 *
 * @returns {*}
 */
App.prototype.loadCondition = function loadCondition() {
  var supportData;

  // supportData = DB.get('support') || {};
  // supportData = DB.get('detail');
  // return _.get(supportData, 'detail');
  return DB.get('support_detail');
};

var app;
$(function() {
  // 初期設定
  configure(data);

  app = new App({
    supportView: new SupportView({
      $el: $('.js-support-view'),
      template: $('#template').text()
    })
  });

  // 初期表示
  app.initialize();
});

/**
 * 表示器カラムの情報を選択したモデルで絞り込み
 *
 * @param columns
 * @param conditions
 * @returns {Array|*}
 */
function filterModelData(columns, conditions) {
  var result, keys, key;

  if (! conditions.length) {
    return columns;
  }

  result = _.filter(columns, function(item) {
    return _.some(conditions, function(val) {
      keys = _.keys(val);

      for (var i = 0, l = keys.length; i < l; i++) {
        key = keys[i];

        // 文字列同士で比較
        if (_.get(item, key)+'' !== _.get(val, key)+'') {
          return false;
        }
      }
      return true;
    });
  });

  return result;
}
