//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
    // Application variable, always include it to have access to app methods.
    'app',
  
    //templates-loader: this loads templates async.
      'js/templates-loader',
      'backgrid',
      'chart',
      'moment',
      'chartjs-date-fns-adapter',
      'modules/navigation-buttons/navigation-buttons',
      'modules/select2-module/select2-module',
      'modules/modal',
      'backgrid/moment-cell',
      'backgrid/grouped-columns',
      'js/multiselect/virtual-select.min',
  
  ],
      function (app, T, Backgrid, ChartJS, moment, ChartJsDateFnsAdapter, NavigationButton, select2Module, Modal) {
  
      var Screen = { Models: {}, Views: {}, Collections: {} }
  
          Screen.Models.Main = Backbone.Epoxy.Model.extend({
  
          defaults: {
              hasData: true,
              isLoading: false,
                  prevHeatName: null,
                  ladleCampaignValue: null,
                  selectedLadleId: null,
                  prevPlateAssembly: null,
                  prevPlateAssmeblyChanged: 0,
                  equipPlateAssemblyId: null,
                  lmPlateAssembly: null,
                  prevPlateAssemblyChanged: 0,
                  prevUpperNozzleChanged: 0,
                  prevUpperNozzle: null,
                  equipUpperNozzleId: null,
                  lmUpperNozzle: null,
                  prevWorkingLining: null,
                  prevWorkingLiningChanged: 0,
                  equipWorkingLiningId: null,
                  lmWorkingLining: null,
                  prevPorousPlugNorthChanged: 0,
                  prevPorousPlugNorth: null,
                  equipPorousPlugNorthId: null,
                  lmPorousPlugNorth: null,
                  prevPorousPlugSouth: null,
                  prevPorousPlugSouthChanged: 0,
                  equipPorousPlugSouthId: null,
                  lmPorousPlugSouth: null,
                  prevTapTime: null,
                  equipmentsCatalogSelect: null,
                  disableButtons: false,
          },
          initialize: function () {
              this.ladleCollection = new Screen.Collections.ItemsColl();
              this.ladleHistoryCollection = new Screen.Collections.ItemsColl();
              this.equipmentsTypes = new Screen.Collections.ItemsColl();
              this.ladleHistoryEquipments = new Screen.Collections.ItemsColl();
              this.equipmentsCatalog = new Screen.Collections.ItemsColl();
  
              },
  
          fetchLadles: function (params) {
              var that = this;
              var qp = new Core.Database.QueryParameters();
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.LAD.GetLadles',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
  
                              if (resp && resp.Table) {           
                                  that.ladleCollection.setDataColl(resp.Table);
                                  that.trigger('ladle-collection-fetched');
                                  that.set({
                                      hasData: false,
                                      isLoading: false,
  
                                  });
                              }
                              else {
                                  if ((resp) && (resp.Message)) {
                                      app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                      console.error(resp.Message);
                                      that.set({
                                          hasData: false,
                                          isLoading: false,                                       
  
                                      });
  
                                  }
                                  else {
                                      app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                      console.error("Server response not valid.");
                                      that.set({
                                          hasData: false,
                                          isLoading: false,                                       
                                      });
                                  }
  
                              }
  
  
                          }
                          catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                      },
                      Secured: true,
                  },
                  app.ConnectionStrings.app
              );
  
              return this;
  
              },
              fetchEquipmentTypes: function (params) {
                  var that = this;
                  var qp = new Core.Database.QueryParameters();
  
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LAD.GetEquipmentTypes',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
  
                                  if (resp && resp.Table) {
                                      that.equipmentsTypes.setDataColl(resp.Table);
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                          that.set({
                                              hasData: false,
                                              isLoading: false,
  
                                          });
  
                                      }
                                      else {
                                          app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                          console.error("Server response not valid.");
                                          that.set({
                                              hasData: false,
                                              isLoading: false,
                                          });
                                      }
  
                                  }
  
  
                              }
                              catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                          },
                          Secured: true,
                      },
                      app.ConnectionStrings.app
                  );
  
                  return this;
  
              },
              fetchLadleInfo: function (params) {
                  var that = this;
                  var qp = new Core.Database.QueryParameters();
  
                  qp.Add('@LadleId', 'INT', params);
  
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LAD.GetLadleInfo',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  that.set({
                                      hasData: false,
                                      isLoading: true,
  
                                  });
  
                                  if (resp && resp.Table) {
                                      that.ladleHistoryCollection.setDataColl(resp.Table);
                                      that.ladleHistoryEquipments.setDataColl(resp.Table1);
                                      that.equipmentsCatalog.setDataColl(resp.Table2);
                                      that.set('equipmentsCatalogSelect', _.map(resp.Table2, function (obj) {
  
                                          return {
                                              id: obj.EquipmentId,
                                              text: obj.Name,
                                              typeId: obj.EquipmentTypeId
                                          };
                                      }));
                                      
                                      that.trigger('ladle-history-fetched');
                                      
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                          that.set({
                                              hasData: false,
                                              isLoading: false,
  
                                          });
  
                                      }
                                      else {
                                          app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                          console.error("Server response not valid.");
                                          that.set({
                                              hasData: false,
                                              isLoading: false,
                                          });
                                      }
  
                                  }
  
  
                              }
                              catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                          },
                          Secured: true,
                      },
                      app.ConnectionStrings.app
                  );
  
                  return this;
  
              },
              disableButtons: function () {
                  var that = this;
                  this.set('disableButtons', true);
                  document.querySelectorAll('.incrementBtn').forEach(element => {
                      element.style.backgroundColor = '#ccc';
                    });
                    document.querySelectorAll('.decrementBtn').forEach(element => {
                      element.style.backgroundColor = '#ccc';
                    });
              },
              enableButtons: function () {
                  var that = this;
                  this.set('disableButtons', true);
                  document.querySelectorAll('.incrementBtn').forEach(element => {
                      element.style.backgroundColor = '#3498db';
                    });
                    document.querySelectorAll('.decrementBtn').forEach(element => {
                      element.style.backgroundColor = '#3498db';
                    });
  
              },
              saveEquipmentSingle: function(params) {
                   var that = this;
                   this.disableButtons();
                   qp = new Core.Database.QueryParameters();
                   this.fixedParameters = [
                      { Name: "@LadleID", Type: "INT", Value: that.get('selectedLadleId'), },
                      { Name: "@EquipmentTypeID", Type: "INT", Value: params.equipmentTypeSelected, },
                      { Name: "@NewValue", Type: "NT", Value: params.value, },
                   ];
  
                   _.each(this.fixedParameters, function (qpParams) {
                      qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                  });
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LAD.ChangeLadleEquipmentSingle',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp) {

                                      if(params.action == 'resetValue') {
                                        app.views.topMessages.showMessage('Reset Lining. Campaign Number Increased', { stay: 5000, });
                                      }
                                      else if (params.action == 'increaseValue') {
                                        app.views.topMessages.showMessage('Heat count increased', { stay: 5000, });
                                      }
                                      else if (params.action == 'decreaseValue') {
                                        app.views.topMessages.showMessage('Heat count decreased', { stay: 5000, });
                                      }
                                      else {
                                        app.views.topMessages.showMessage('Heat count changed', { stay: 5000, });
                                      }
                                      
                                      that.trigger('equipment-changed');
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
  
                                          console.error(new Error(resp.Message).stack);
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          that.trigger('equipment-changed');
                                      }
                                      else {
                                          console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                          app.views.topMessages.showMessage('SERVER_RESPONSE_NOT_VALID', { stay: 5000, });
                                          that.trigger('equipment-changed');
                                      }
                                          
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: false,
                      },
                      app.ConnectionStrings.app
                  );
  
                  return this;
              },
  
              changeLadlePosition: function (params) {
                  var that = this;
                  qp = new Core.Database.QueryParameters();
  
                  this.fixedParameters = [
                      { Name: "@LadleId", Type: "INT", Value: params.LadleId, },
                      { Name: "@LadlePositionId", Type: "INT", Value: params.LadlePositionId, },
                      { Name: "@GodMode", Type: "BIT", Value: true, },
                  ];
  
  
                  _.each(this.fixedParameters, function (qpParams) {
                      qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                  });
  
  
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LAD.ChangeLadlePositionWeb',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp.Table) {
                                      console.log(resp);
                                      app.views.topMessages.showMessage('Ladle '+params.LadleId+ ' sent to '+ params.Destination , { stay: 5000, });
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
  
                                          console.error(new Error(resp.Message).stack);
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                      }
                                      else {
                                          console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                          app.views.topMessages.showMessage('SERVER_RESPONSE_NOT_VALID', { stay: 5000, });
                                      }
  
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: true,
                      },
                      app.ConnectionStrings.app
                  );
  
                  return this;
  
              },
  
      });
  
          Screen.Views.Main = Backbone.Epoxy.View.extend({
              template: 'ladle-wall-manager',
              id: 'ladle-wall-manager',
              title: 'Ladle Wall Manager',
              isCacheable: false,
              events: function () {
                  return {
                      'click #refreshBtn': this.refreshBtn_click,
                      'click .incrementBtn': this.increaseValue,
                      'click .decrementBtn': this.decreaseValue,
                      'click .resetBtn': this.resetValue,
                      'click .restoreBtn': this.restoreValue,
                      'change select': this.selectChanged,
                      'click #saveBtn': this.saveChanges,
                      'click #cancelBtn': this.cancelChanges,
                      'click #drainBtn': this.drainLadle,
                      'click #sendtoFABtn': this.sendToEAFA,
                      'click #sendtoFBBtn': this.sendToEAFB,
                      'click #sendToMaintenanceBtn': this.sendToMaintenance,
                  };
              },
              bindings: 'data-bind',
              subviews: null,
              viewParams: null,
              autoRefresh: null,
              pauseTimer: false,
  
              initialize: function () {
                  this.options.state = app.view_states.loading;
                  this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };
  
                  var that = this;
                  this.model = new Screen.Models.Main();
  
                  this.autoRefresh = {
                      enabled: null
                      , toid: null
                      , every: 5 * 1000
                  };
  
                  this.bindEvents();
  
              },
              bindEvents: function () {
                  this.listenTo(this.model, 'ladle-collection-fetched', this.ladleSubNavBar)
                      .listenTo(this.model, 'equipment-changed', this.saveComplete)
                      .listenTo(this.model, 'change:prevWorkingLining change:prevUpperNozzle change:prevPorousPlugNorth change:prevPlateAssembly change:prevPorousPlugSouth', this.validateInput)
                      .listenTo(this.model, 'ladle-history-fetched', this.populateTable);
              },
              cancelChanges: function () {
                  this.populateTable();    
              },
  
  
              sendToEAFA: function () {
  
                  var that = this;
                  modal = new Modal.Views.Main({
                      focusOk: false,
                      focusSelector: '#btn-cancel',
                      title: "Send to EAF",
                      message: "Are you sure you want to send Ladle: " + that.model.get('selectedLadleId') + " to Furnace A?",
                      buttons_type: "CONTINUE-CANCEL",
                  });
  
                  this.listenToOnce(modal, "continue", function (modal) {
                      try {
                          that.model.changeLadlePosition({ LadleId: that.model.get('selectedLadleId'), LadlePositionId: 1, Destination: 'FURNACE A' });
  
                          that.refresh();
                      }
                      catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                  });
  
                  modal.show();
              },
              sendToEAFB: function () {
                  var that = this;
                  modal = new Modal.Views.Main({
                      focusOk: false,
                      focusSelector: '#btn-cancel',
                      title: "Send to EAF",
                      message: "Are you sure you want to send Ladle: " + that.model.get('selectedLadleId') + " to Furnace B?",
                      buttons_type: "CONTINUE-CANCEL",
                  });
  
                  this.listenToOnce(modal, "continue", function (modal) {
                      try {
                          that.model.changeLadlePosition({ LadleId: that.model.get('selectedLadleId'), LadlePositionId: 3, Destination: 'FURNACE B' });
  
                          that.refresh();
                      }
                      catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                  });
  
                  modal.show();
              },
  
              sendToMaintenance: function () {
                  var that = this;
                  modal = new Modal.Views.Main({
                      focusOk: false,
                      focusSelector: '#btn-cancel',
                      title: "Send to EAF",
                      message: "Are you sure you want to send Ladle: " + that.model.get('selectedLadleId') + " to Maintenance?",
                      buttons_type: "CONTINUE-CANCEL",
                  });
  
                  this.listenToOnce(modal, "continue", function (modal) {
                      try {
                          that.model.changeLadlePosition({ LadleId: that.model.get('selectedLadleId'), LadlePositionId: 70, Destination: 'MAINTENANCE' });
  
                          that.refresh();
                      }
                      catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                  });
  
                  modal.show();
              },
  
              validateInput: function () {
                  console.log();
                  var that = this;
                  // check what input changed
                  const inputChanged = Object.keys(this.model.changed)[0];
                  //get the HTML Tag changed
                  const inputTag = document.getElementById(inputChanged);
  
                  //Get the value
                  const valueInput = Object.keys(this.model.changed).map(x => this.model.changed[x])[0];
  
  
                  //look for alarm and warning in the collection based in the Name attribute in the HTML Tag
                  //var model = this.model.equipmentsTypes.models.filter(x => x.get('Key') == inputTag.getAttribute('name'))[0];
                  var model = that.model.ladleHistoryEquipments.models.filter(x => x.get('Key') == inputTag.getAttribute('name'))[0];
  
  
                  if (valueInput >= model.get('Alarm')) {
                      inputTag.classList.add('highlight-input-danger');
                  }
                  else if (valueInput >= model.get('Warning') && valueInput < model.get('Alarm')) {
                      inputTag.classList.add('highlight-input-warning');
                  }
                  else {
                      inputTag.classList.remove('highlight-input-danger');
                      inputTag.classList.remove('highlight-input-warning');
                  }
  
              },
  
              renderSelectInputs: function () {
  
                  var that = this;
                  //get Input Id to map select
                  var inputElArr = this.$('select');
  
                  _.each(inputElArr, function (inputTag) {
                      //Fitler catalog to only show by type
                      var model = that.model.ladleHistoryEquipments.models.filter(x => x.get('Key') == inputTag.getAttribute('name'))[0];
                      var dataSelect = that.model.get('equipmentsCatalogSelect').filter(x => x.typeId == model.get('TypeId'));
                      const equipmentSelect = new select2Module.Views.Main({
                          el: inputTag,
                          data: dataSelect,
                          disabledByDefault: false,
                          tagging: false,
                          tags: false,
                      });
  
                      //get the current Equipment Id selected
                      const currentEquipment = dataSelect.filter(x => x.id == model.get('EquipmentID'))[0].id;
                      $(inputTag).val(currentEquipment).trigger('change');
                  });
  
                  that.model.set({
                      hasData: true,
                      isLoading: false,
  
                  });
              },
              drainLadle: function () {
                  var that = this;
                  var qp = qp = new Core.Database.QueryParameters();
  
                  qp.Add('@LadleID', 'INT', that.model.get('selectedLadleId'));
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LAD.DrainLadle',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp) {
                                      app.views.topMessages.showMessage('Ladle ' + that.model.get('selectedLadleId') + 'Drained', { stay: 2000, });
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          console.error(new Error(resp.Message).stack);
                                          app.views.topMessages.showMessage(resp.Message, { stay: 2000, });
  
                                      }
                                          
  
                                      else {
                                          app.views.topMessages.showMessage('SERVER_RESPONSE_NOT_VALID', { stay: 2000, });
                                          console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                      }
                                          
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: true,
                      },
                      app.ConnectionStrings.app
                  );
  
                  return this;
              },
              resetValue: function (e) {
                  var that = this;
                  //get the input changed
                  var input = e.target.closest('tr').querySelector('input[type="number"]');
  
                  //reset to zero
                  that.model.set(input.id, 0);
                  if(!that.model.get('disableButtons')) {
                      input.value = 0;
                      that.model.set(input.getAttribute('id'), parseInt(input.value, 10));
                      var equipmentTypeSelected = that.model.equipmentsTypes.filter( x => x.get('Key') == input.name)[0].get('Id');
                      var value = parseInt(input.value, 10);
                      var params = { equipmentTypeSelected : equipmentTypeSelected, value : value, action: 'resetValue' }
                      that.model.saveEquipmentSingle(params);
                  }
              },
  
              restoreValue: function (e) {
                  var that = this;
                  //get the input changed
                  var input = e.target.closest('tr').querySelector('input[type="number"]');
                  //get the original model value based on the key selected (Matched in Name attribute in input)
                  const originalModel = this.model.ladleHistoryEquipments.filter(x => x.get('HeatId') == that.model.get('prevHeatName') && x.get('Key') == input.getAttribute('Name'))[0];
  
                  //restore original value
                  that.model.set(input.id, originalModel.get('CampaignCounter'));
                  // Check if the element has the 'resetBtn' class
                  if (e.target.classList.contains("restoreBtn")) {
                      // If it does, remove the class
                      e.target.classList.remove("restoreBtn");
                      e.target.classList.add("resetBtn");
                      e.target.innerHTML = 'Reset';
                  }
              },
  
              saveComplete: function () {
                  var that = this;
                  that.enableButtons();
                  that.refresh();
              },
  
              ladleSubNavBar: function () {
                  var that = this;
                  _.each(this.model.ladleCollection.sortBy('Id'), function (model) {
  
                      const name = model.get('Name');
                      const ladleId = model.get('Id');
                      const button = $('<button>').text(ladleId);
  
                      button.addClass('btn-ladle-navbar');
                      button.on('click', function () {
                          $('.btn-ladle-navbar').removeClass('highlight-ladle');
                          button.addClass('highlight-ladle');
                          that.model.fetchLadleInfo(ladleId);
                          that.model.set('selectedLadleId', ladleId);
                          that.model.set({
                              isLoading: true,
                              hasData: false,
                          });
                          
                      });
                      $('.ladle-container').append(button);
                  });
              },
              selectChanged: function (event) {
                  var that = this;
                  console.log();
                  const selectTag = $(event.target);
                  //match select and input by Name attribute
                  const tagName = selectTag[0].getAttribute('Name');
                  const inputSelectId = this.$('input[name="' + tagName + '"]')[0].id;
                  const inputTag = this.$('input[name="' + tagName + '"]');
  
                  // check if match original value if not, reset to 0
                  const originalModel = this.model.ladleHistoryEquipments.filter(x => x.get('HeatId') == this.model.get('prevHeatName') && x.get('EquipmentID') == selectTag.val());
                  if (originalModel.length > 0) {
                      // Restore the original value
                      that.model.set(inputSelectId, originalModel[0].get('CampaignCounter'));
                      
                  } else {
                      // Set the value to 0
                      that.model.set(inputSelectId, 0);
  
                  }
                  // set the attribute in model
                  that.model.set('equip' + tagName + 'Id', selectTag.val())
              },
              populateTable: function () {
                  var that = this;
                  console.log();
                  
                  that.model.set('prevHeatName', that.model.ladleHistoryCollection.at(0).get('HeatId'));
                  that.model.set('ladleCampaignValue', that.model.ladleHistoryCollection.at(0).get('Campaign'));
                  that.model.set('prevPlateAssembly', that.model.ladleHistoryCollection.at(0).get('PlateAssembly'));
                  that.model.set('prevUpperNozzle', that.model.ladleHistoryCollection.at(0).get('UpperNozzle'));
                  that.model.set('prevWorkingLining', that.model.ladleHistoryCollection.at(0).get('WorkingLining'));
                  that.model.set('prevPorousPlugNorth', that.model.ladleHistoryCollection.at(0).get('PorousPlugNorth'));
                  that.model.set('prevPorousPlugSouth', that.model.ladleHistoryCollection.at(0).get('PorousPlugSouth'));
  
                  that.model.set('lmPlateAssembly', new moment(that.model.ladleHistoryEquipments.filter(x => x.get('Key') == 'PlateAssembly')[0].get('LastModified')).format('YYYY-MM-DD HH:mm:ss'));
                  that.model.set('lmUpperNozzle', new moment(that.model.ladleHistoryEquipments.filter(x => x.get('Key') == 'UpperNozzle')[0].get('LastModified')).format('YYYY-MM-DD HH:mm:ss'));
                  that.model.set('lmWorkingLining', new moment(that.model.ladleHistoryEquipments.filter(x => x.get('Key') == 'WorkingLining')[0].get('LastModified')).format('YYYY-MM-DD HH:mm:ss'))
                  that.model.set('lmPorousPlugNorth', new moment(that.model.ladleHistoryEquipments.filter(x => x.get('Key') == 'PorousPlugNorth')[0].get('LastModified')).format('YYYY-MM-DD HH:mm:ss'))
                  that.model.set('lmPorousPlugSouth', new moment(that.model.ladleHistoryEquipments.filter(x => x.get('Key') == 'PorousPlugSouth')[0].get('LastModified')).format('YYYY-MM-DD HH:mm:ss'))
  
                  var tapTime = that.model.ladleHistoryCollection.at(0).get('TapTime');
                  that.model.set('prevTapTime', (tapTime == null ? '' : new moment(tapTime).format('YYYY-MM-DD HH:mm:ss')) );
  
                  that.renderSelectInputs();
  
              },
              render: function (container, urlParams) {
                  var that = this;
                  var thatContainer = (this.options.container) ? this.options.container : container;
                  this.options.container = thatContainer;
  
                  var customPath = '/app/custom-screens/' + this.template + '/';
  
                  T.render.call(
                      this,
                      this.template,
                      function (tmp) {
                          if (!that.options.i18n) that.options.i18n = {};
  
                          app.getI18NJed(
                              that,
                              that.template,
                              function (i18nJED) {
                                  that.options.i18n[that.template] = i18nJED;
                                  that.$el.html(tmp());
  
                                  that.applyBindings();
  
                                  //appending view to the main container
                                  that.model.fetchLadles();
                                  that.model.fetchEquipmentTypes();
                                  //that.renderSelectInputs();
                                  that.append(thatContainer, that.$el);
  
                                  //that.refresh();
  
                                  //that.startAutoRefresh();
  
                              },
                              true,
                              customPath
                          );
                      },
                      customPath
                  );
              },
              refresh: function (isAutoRefresh) {
                  this.model.set({
                      isLoading: true,
                      hasData: false,
                  });
                  this.model.set('prevHeatName', null);
                  this.model.set('prevPlateAssembly', null);
                  this.model.set('prevUpperNozzle', null);
                  this.model.set('prevWorkingLining', null);
                  this.model.set('prevPorousPlugNorth',null);
                  this.model.set('prevPorousPlugSouth', null);
                  this.model.set('prevTapTime', null);
                  var selectedLadle = this.model.get('selectedLadleId')
                  this.model.fetchLadleInfo(selectedLadle != null ? selectedLadle : 1);
              },
              process_fetched: function () {
                  this.model.set({
                      isLoading: false,
                      hasData: true,
                  });
              },
  
          refreshBtn_click: function (e) {
              this.refresh();
  
              },
              increaseValue: function (e) {
                  var that = this;
                  var input = null;
                  if (e.target.nodeName == 'BUTTON') {
                       input = e.target.previousElementSibling;
                  }
                  else {
                       input = e.target.parentElement.previousElementSibling;
                  }
                  
                  if(!that.model.get('disableButtons')) {
                      input.value++;
                      that.model.set(input.getAttribute('id'), parseInt(input.value, 10));
                      var equipmentTypeSelected = that.model.equipmentsTypes.filter( x => x.get('Key') == input.name)[0].get('Id');
                      var value = parseInt(input.value, 10);
                      var params = { equipmentTypeSelected : equipmentTypeSelected, value : value , action: 'increaseValue'}
                      that.model.saveEquipmentSingle(params);
                  }
                  
              },
              decreaseValue: function (e) {
                  var that = this;
                  var input = null;
                  if (e.target.nodeName == 'BUTTON') {
                       input = e.target.nextElementSibling;
                  }
                  else {
                       input = e.target.parentElement.nextElementSibling;
                  }
                 
                  if(!that.model.get('disableButtons')) {
                      input.value--;
                      that.model.set(input.getAttribute('id'), parseInt(input.value, 10));
                      var equipmentTypeSelected = that.model.equipmentsTypes.filter( x => x.get('Key') == input.name)[0].get('Id');
                      var value = parseInt(input.value, 10);
                      var params = { equipmentTypeSelected : equipmentTypeSelected, value : value , action: 'decreaseValue'}
                      that.model.saveEquipmentSingle(params);
                  }
                
              },
              disableButtons: function () {
                  var that = this;
                  that.model.set('disableButtons', true);
                  document.querySelectorAll('.incrementBtn').forEach(element => {
                      element.style.backgroundColor = '#ccc';
                    });
                    document.querySelectorAll('.decrementBtn').forEach(element => {
                      element.style.backgroundColor = '#ccc';
                    });
              },
              enableButtons: function () {
                  var that = this;
                  that.model.set('disableButtons', false);
                  document.querySelectorAll('.incrementBtn').forEach(element => {
                      element.style.backgroundColor = '#3498db';
                    });
                    document.querySelectorAll('.decrementBtn').forEach(element => {
                      element.style.backgroundColor = '#3498db';
                    });
  
              },
  
              //Auto refresh
              _refresh: function (opt) {
                  if (this.autoRefresh.toid != null) {
                      clearTimeout(this.autoRefresh.toid);
                      this.autoRefresh.toid = null;
                  }
  
                  if (!this.pauseTimer) {
                      var isAutoRefresh = true;
                      this.refresh(isAutoRefresh);
                  } 
  
                  if (this.autoRefresh.enabled == true) {
                      var that = this;
  
                      this.autoRefresh.toid = setTimeout(
                          function () { that._refresh(); },
                          this.autoRefresh.every
                      );
                  }
              },
              startAutoRefresh: function () {
                  try {
                      if (this.autoRefresh.enabled !== true) {
                          var that = this;
  
                          if (this.autoRefresh.toid != null) {
                              clearTimeout(this.autoRefresh.toid);
                              this.autoRefresh.toid = null;
                          }
  
                          this.autoRefresh.enabled = true;
  
                          //use a timeout to execute the first refresh to return the handle to the start function caller.
                          //So when the caller finish it will do the first refresh.
                          this.autoRefresh.toid = setTimeout(
                              function () { that._refresh(); },
                              1
                          );
                      }
                  } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
              },
              stopAutoRefresh: function () {
                  if (this.autoRefresh.toid != null) {
                      clearTimeout(this.autoRefresh.toid);
                      this.autoRefresh.toid = null;
                  }
                  this.autoRefresh.enabled = false;
              },
  
          append: function (container, el) {
              el = (el != null && el != undefined) ? el : this.$el;
  
              if (this.options.state == app.view_states.loading
                  || this.options.state == app.view_states.shown) {
                  //appending view to the main container and set state to shown
  
                  this.options.state = app.view_states.shown;
                  container.append(el);
  
                  this.options.onappend(this);
              }
  
              if (this.options.state == app.view_states.hidden) {
                  //append and remain hidden
                  container.append(el);
              }
  
              if (this.options.state == app.view_states.closed) {
                  //return without appending.
                  return;
              }
          },
          bindViewScopedEvents: function () {
              var that = this;
          },
          unbindViewScopedEvents: function () {
  
          },
          close: function () {
              this.options.state = app.view_states.closed;
              this.stopAutoRefresh();
              this.closeSubviews();
              this.remove();
              this.unbindViewScopedEvents();
              this.unbind();
          },
          closeSubviews: function () {
              _.each(this.subviews, function (sview) {
                  sview.close();
              });
          },
          show: function () {
              this.options.state = app.view_states.shown;
  
              this.showSubviews();
              this.bindEvents();
              this.$el.show();
          },
          showSubviews: function () {
              _.each(this.subviews, function (sview) {
                  sview.show();
              });
          },
          hide: function () {
              this.options.state = app.view_states.hidden;
  
              this.hideSubviews();
  
              this.$el.hide();
              this.unbind();
              this.stopListening();
          },
          hideSubviews: function () {
              _.each(this.subviews, function (sview) {
                  sview.hide();
              });
          },
          preRender: function () {
              app.models.subnavbar.set("subnavbar", false);
          },
          reRender: function (urlParams) {
              try {
                  this.refresh(viewParams);
              } catch (Error) { }
          },
  
      });
  
      Screen.Collections.ItemsColl = Backbone.Collection.extend({
          setDataColl: function (data) {
              var newColl,
                  that = this;
              newColl = data;
              that.set(newColl).trigger('fetch', that, data);
          },
      });
  
  
      // Required, return the module for AMD compliance.
      return Screen;
  });