﻿/*
Copyright 2017 apHarmony

This file is part of jsHarmony.

jsHarmony is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

jsHarmony is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this package.  If not, see <http://www.gnu.org/licenses/>.
*/
<% if(model.sample_data) return; %>

<%  
var lovfield = '';
for(var i=0;i<model.fields.length;i++){ 
  var field = model.fields[i];
  if(field.lov){ 
    if(lovfield != '') throw new Error('Can only have one LOV per Multisel.');
    lovfield = field.name; 
  }
}
if(lovfield == '') throw new Error('Multisel requires one LOV.');
%>

(function(jsh){
  var _ = jsh._;
  var $ = jsh.$;
  var XExt = jsh.XExt;
  var xgrid = null;
  var xform = null;
  var modelid = '<%=model.id%>';
  var xmodel = jsh.XModels[modelid];

  var xcontroller = xmodel.controller = new XExt.XModel.XController(xmodel);

  xcontroller.Init = function(callback){
    xgrid = xcontroller.grid = new jsh.XGrid({ modelid: modelid });
    xform = xcontroller.form = new jsh.XForm(modelid);
    xgrid.HasUpdates = function(){ return false; };
    xgrid.Data = {};
    xgrid.PlaceholderID = '.xmultisel_'+xmodel.class+'_placeholder';
    xgrid.TemplateID = '.xmultisel_'+xmodel.class+'_template';

    xgrid.Select = function(onComplete){
      var execparams = {};

      if(jsh.is_insert){}
      else if(jsh.is_browse) execparams._action = 'browse';

      //Pass parameters from bindings
      if(!jsh.is_insert){
        for(var fieldname in xmodel.bindings){
          var bfield = xmodel.fields[fieldname];
          if((typeof bfield != 'undefined') && (jsh.XExt.hasAction(bfield.actions,'F'))){
            execparams[fieldname] = xmodel.bindings[fieldname]();
          }
        }
      }
      else{
        for(var fieldname in xmodel.bindings){
          var bfield = xmodel.fields[fieldname];
          if((typeof bfield != 'undefined') && (bfield.lovkey)){
            var val = xmodel.bindings[fieldname]();
            if(typeof val != 'undefined') execparams[fieldname] = val;
          }
        }
      }

      jsh.xLoader.StartLoading(xgrid);
      var _query = '';
      if(!_.isEmpty(execparams)) _query = '?'+$.param(execparams);
      $.ajax({
        type:"GET",
        cache: false,
        url:jsh._BASEURL+'_d/'+xgrid.modelid+'/'+_query,
        dataType: 'json',
        success:function(data){
          if((data instanceof Object) && ('_error' in data)){
            if(jsh.DefaultErrorHandler(data['_error'].Number,data['_error'].Message)) { }
            else if(data._error.Number == -9){ jsh.XExt.Alert(data._error.Message); }
            else { jsh.XExt.Alert('Error #'+data._error.Number+': '+data._error.Message); }
          }
          else{
            var ejssource = jsh.$root(xgrid.TemplateID).html();
            ejssource = ejssource.replace(/<#/g,'<'+'%').replace(/#>/g,'%'+'>')
            if('_title' in data) xgrid.title = data._title;
            var ejsrslt = jsh.XExt.renderEJS(ejssource, modelid, {
              datatable:data[xgrid.modelid]
            });
            jsh.$root(xgrid.PlaceholderID).empty();
            jsh.$root(xgrid.PlaceholderID).append(ejsrslt);

            //Attach events
            jsh.$root('.xelem'+xmodel.class).keyup(function(){ if(!$(this).hasClass('editable')) return; xcontroller.OnControlUpdate(this); });
            jsh.$root('.xelem'+xmodel.class+'.checkbox').change(function(){ if(!$(this).hasClass('editable')) return; xcontroller.OnControlUpdate(this); });
          }
          jsh.xLoader.StopLoading(xgrid);
          if(onComplete) onComplete();
        }
      });
    };

    callback();
  }

  xcontroller.OnControlUpdate = function(obj){
    var jobj = $(obj);
    var curval = jobj.is(':checked');
    var origval = !!jobj.data('orig-checked');
    jobj.parent().toggleClass('updated',curval!=origval);
  }

  xcontroller.Save = function(){
    var selected_values = [];
    jsh.$root(xgrid.PlaceholderID+' input.xselitem').each(function(i,obj){
      if($(obj).is(':checked')){
        selected_values.push($(obj).val());
      }
    });
    var _query = {};
    //Pass parameters from bindings
    for(var fieldname in xmodel.bindings){
      var bfield = xmodel.fields[fieldname];
      if((typeof bfield != 'undefined') && !(jsh.XExt.hasAction(bfield.actions,'F'))) continue;
      _query[fieldname] = xmodel.bindings[fieldname]();
      if(jsh.is_insert && XExt.isNullUndefinedEmpty(_query[fieldname])){
        _query[fieldname] = '%%%'+fieldname+'%%%';
      }
    }
    var rslt = { 
      'method':'post',
      'model':xgrid.modelid,
      'query':_query,
      'post':{'<%=lovfield%>':JSON.stringify(selected_values)},
      'onComplete':undefined
    };
    return [rslt];
  }

})(<%-instance%>);

<%-jsh.RenderView('jsh_multisel.js.datamodel',ejsparams)%>