
var oCusEvents = [];
var idCnt = 0 ;
var boDebug = true ;

/* ---------------------------------------------------------------------------
 *
 */
function dbg( sMessage ) {
  if( boDebug == true ) {
    console.log( sMessage );
  }
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_getId() {
  idCnt ++ ;
  return 'id' + idCnt ;
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_test() {
  dbg( "this is a test" );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_addEvent() {
  oCusEvents.push( {event:0, param:"", actions:[] } );
  fcn_createCusEventsTable();
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_addAction( evntId ) {
  for( let i = 0; i < oCusEvents.length; i++ ) {
    if( oCusEvents[i].id == evntId ) {
      if( typeof oCusEvents[i].actions === 'undefined' ) {
        oCusEvents[i].actions = [] ;
      } 
      oCusEvents[i].actions.push( {action:0, delay:0, param:"" } );
      dbg( 'added action to event "' + evntId +  '"' );
      fcn_createCusEventsTable();
      return;
    }
  }
};



/* ---------------------------------------------------------------------------
 *
 */
function fcn_removeEvent( idx ) {
  dbg( 'remove event ' + idx );
  if( idx < oCusEvents.length ) {
    oCusEvents.splice( idx, 1 );
  }
  fcn_createCusEventsTable();
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_removeAction( idAction ) {
  dbg( 'remove action ' + idAction );    
  for( let i = 0; i < oCusEvents.length; i++ ) { 
    for( let a = 0; a < oCusEvents[i].actions.length; a++ ) {
      if( oCusEvents[i].actions[a].id == idAction ) {
        dbg( 'found action to remove' ); 
        oCusEvents[i].actions.splice( a, 1 );
        fcn_createCusEventsTable();
        return;
      }
    }
  }
}

/* ---------------------------------------------------------------------------
 *
 */
function fcn_getHtmlDropdown( onChange, arOptions, sId, sValue ) { 
  var dd = document.createElement('select');
  if( typeof sId !== 'undefined' ) {
    dd.id = sId;                  
    dd.setAttribute('id', sId );
  }
  if( typeof sValue !== 'undefined' ) {
    sValue = String( sValue ) ;
  } else {
    sValue = "";
  }
  dd.setAttribute('onchange', onChange );
  var idxSelect = 0 ;              
  
  // get the selection index
  for( let o=0; o<arOptions.length; o++ ) { 
    if( arOptions[o].value == sValue ) {
      idxSelect = o;
    }
  }
  
  for( let o=0; o<arOptions.length; o++ ) {
    opt = document.createElement('option');
    opt.textContent = arOptions[o].text ;
    opt.value       = arOptions[o].value ;
    if( idxSelect == o ) {
      opt.selected  = "selected" ;
    }
    dd.appendChild( opt );
  }
  return dd;
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_getHtmlDropdownForImages( onChange, sId, sCurrentValue ) {

  var arOptions = [];
  for( var i = 0; i < refImages.length; i++ ) {
    arOptions.push( { text : refImages[ i ], value : refImages[ i ] } );
  }
  return fcn_getHtmlDropdown( onChange, arOptions, sId, sCurrentValue ) ;
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_retrieveEventParam() {
  // assume oData is an array
  dbg( 'retrieve all param values' );
  for( let i = 0; i < oCusEvents.length; i++ ) {
    var evntId = oCusEvents[i].id ;
    var sParam = "";
    for( let p=0; p<10; p ++ ) {
      var oInp = document.getElementById( evntId + '_par' + p );
      if( typeof oInp !== 'undefined' && oInp != null ) {
        if( p > 0 ) {
          sParam = sParam + '|';
        }
        sParam = sParam + oInp.value;
      } else {
        break;
      }
    }
    oCusEvents[i].param = sParam;
    for( let a = 0; a < oCusEvents[i].actions.length; a++ ) {
      var actionId = oCusEvents[i].actions[a].id ;
      var sParam = "";
      for( let p=0; p<10; p ++ ) {
        var oInp = document.getElementById( actionId + '_par' + p );
        if( typeof oInp !== 'undefined' && oInp != null ) {
          if( p > 0 ) {
            sParam = sParam + '|';
          }
          sParam = sParam + oInp.value;
        } else {
          break;
        }
      }                                      
      oCusEvents[i].actions[a].delay = parseInt( document.getElementById( actionId + '_delay' ).value ) ;
      oCusEvents[i].actions[a].param = sParam;
    }
  }
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_changeEventParam( evntId, boReload ) {
  // assume oData is an array
  for( let i = 0; i < oCusEvents.length; i++ ) {
    if( oCusEvents[i].id == evntId ) {
      var sParam = "";
      for( let p=0; p<10; p ++ ) { 
        var oInp = document.getElementById( evntId + '_par' + p );
        if( typeof oInp !== 'undefined' && oInp != null ) {
          dbg( 'found param input : "' + evntId + '_par' + p + '"' );
          if( p > 0 ) {
            sParam = sParam + '|';
          } 
          sParam = sParam + oInp.value;
        } else {
          dbg( 'event "' + evntId + '" param count: ' + p );
          break;
        }
      }
      oCusEvents[i].param = sParam;
      dbg( 'change event params of "' + evntId + '" to "' + sParam + '"' );
      if( boReload == true ) {
        fcn_createCusEventsTable();
      }
      return;
    }
  }
  dbg( 'event "' + evntId + '" not found' );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_changeEventActionParam( actionId, boReload ) {
  // assume oData is an array
  for( let i = 0; i < oCusEvents.length; i++ ) {
    for( let a = 0; a < oCusEvents[i].actions.length; a++ ) {
      if( oCusEvents[i].actions[a].id == actionId ) {
        var sParam = "";
        oCusEvents[i].actions[a].delay = parseInt( document.getElementById( actionId + '_delay' ).value ) ;
        for( let p=0; p<10; p ++ ) { 
          var oInp = document.getElementById( actionId + '_par' + p );
          if( typeof oInp !== 'undefined' && oInp != null ) {
            dbg( 'found action param input : "' + actionId + '_par' + p + '"' );
            if( p > 0 ) {
              sParam = sParam + '|';
            } 
            sParam = sParam + oInp.value;
          } else {
            dbg( 'action "' + actionId + '" param count: ' + p );
            break;
          }
        }
        oCusEvents[i].actions[a].param = sParam;
        dbg( 'change event action params of "' + actionId + '" to "' + sParam + '", delay to ' + oCusEvents[i].actions[a].delay );
        if( boReload == true ) {
          fcn_createCusEventsTable();
        }
        return;
      }
    }
  }
  dbg( 'event "' + evntId + '" not found' );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_changeEventType( evntId, value ) {
  // assume oData is an array
  for( let i = 0; i < oCusEvents.length; i++ ) {
    if( oCusEvents[i].id == evntId ) {
      oCusEvents[i].event = parseInt( value );
      oCusEvents[i].param = "";
      dbg( 'change event type of "' + evntId + '" to value ' + value );
      fcn_createCusEventsTable();
      return;
    }
  }
  dbg( 'event "' + evntId + '" not found' );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_changeEventActionType( actionId, value ) {
  // assume oData is an array
  for( let i = 0; i < oCusEvents.length; i++ ) {  
    for( let a = 0; a < oCusEvents[i].actions.length; a++ ) {
      if( oCusEvents[i].actions[a].id == actionId ) {
        oCusEvents[i].actions[a].action = parseInt( value );
        oCusEvents[i].actions[a].param = "";
        dbg( 'change action type of "' + actionId + '" to value ' + value );
        fcn_createCusEventsTable();
        return;
      }
    }
  }
  dbg( 'action "' + evntId + '" not found' );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_getHtmlForEvent( ref_tr, evnt, idx ) { 
  const tdBtnRm = document.createElement('td');
  
  // button to remove event
  const btnRemove = document.createElement('button');
  btnRemove.textContent = '-';   
  btnRemove.setAttribute('onclick', 'fcn_removeEvent( ' + idx + ' );');
  tdBtnRm.appendChild( btnRemove );
  ref_tr.appendChild( tdBtnRm );
  
  if( typeof evnt.actions === 'undefined' ) {
    evnt.actions = [] ;
  }
  
  // event content
  const tdEvent = document.createElement('td');
  tdEvent.style.border = '1px solid black';
  
  tdEvent.appendChild( fcn_getHtmlDropdown( 'fcn_changeEventType("' + evnt.id + '", this.value );',
    [ {text: translations[0], value: 0 },
      {text: translations[1], value: 1 }
    ], null, evnt.event ) );
  
  var arParams = evnt.param.split('|');
  var sChangeFcn = 'fcn_changeEventParam("' + evnt.id + '", true );';
  
  switch( evnt.event ) {
    case 0: // key event
      var parKeyIdx   = 0; //valid 0,7,9,10,11
      var parKeyEvent = 0; //valid 0,7,9,10,11
      var parKeyTime  = 0;
      
      if( arParams.length > 0 ) {
        parKeyIdx   = parseInt( arParams[ 0 ] );
      }
      if( arParams.length > 1 ) {
        parKeyEvent = parseInt( arParams[ 1 ] );
      }
      if( arParams.length > 2 ) {
        parKeyTime  = parseInt( arParams[ 2 ] );
      }
      
      const divKey = document.createElement('div');
      
      divKey.appendChild( fcn_getHtmlDropdown( sChangeFcn,
        [ {text: 'key 0',  value: 0  },
          {text: 'key 7',  value: 7  },
          {text: 'key 9',  value: 9  },
          {text: 'key 10', value: 10 }
        ], evnt.id + '_par0', parKeyIdx ) );
        
      divKey.appendChild( fcn_getHtmlDropdown( sChangeFcn,
        [ {text: 'key down', value: 0 },
          {text: 'key up',   value: 1 },
          {text: 'key timed press',   value: 2 }
        ], evnt.id + '_par1', parKeyEvent ) );
        
      const inpKeyTime = document.createElement('input');
      inpKeyTime.id = evnt.id + '_par2';
      inpKeyTime.type = "text";
      inpKeyTime.value = parKeyTime ;  
      inpKeyTime.setAttribute('onchange', sChangeFcn );
      divKey.appendChild( inpKeyTime );
        
      divKey.appendChild( document.createElement('br') );
      tdEvent.appendChild( divKey );
      break;
      
    case 1: // img upd to   
      const divTmp = document.createElement('div');
      divTmp.appendChild( fcn_getHtmlDropdownForImages( sChangeFcn, evnt.id + '_par0', evnt.param ) );
      tdEvent.appendChild( divTmp );
      break;
      
    default:
      dbg( 'invalid event type "' + evnt.event + '"' );
      break;
  }
    
  if( boDebug == true ) {
    tdEvent.appendChild(document.createTextNode('[' + idx + '] event (type ' + evnt.event + ')' ) );
  }
  
  const tblAction = document.createElement('table');
  //tbl.style.width = '100px';
  tblAction.style.border = '1px solid black';
  
  for( let a = 0; a < evnt.actions.length; a++ ) {
    const trAction = tblAction.insertRow();
    tdActionRem = trAction.insertCell();
    
    evnt.actions[a].id = fcn_getId();
    
    var sChangeActionFcn = 'fcn_changeEventActionParam("' + evnt.actions[a].id + '", true );'; 
    
    const btnRmAct = document.createElement('button');
    btnRmAct.textContent = '-';   
    btnRmAct.setAttribute('onclick', 'fcn_removeAction( "' + evnt.actions[a].id + '" );');       
    tdActionRem.appendChild( btnRmAct );
     
    const tdActionContent = trAction.insertCell(); 
    tdActionContent.style.border = '1px solid black';
    tdActionContent.appendChild(document.createTextNode( translations[2] + ':' ) );
        
    const inpDelay = document.createElement('input');
    inpDelay.id = evnt.actions[a].id + '_delay';
    inpDelay.type = "text";
    inpDelay.value = evnt.actions[a].delay ;  
    inpDelay.setAttribute('onchange', sChangeActionFcn );
    tdActionContent.appendChild( inpDelay );
  
    tdActionContent.appendChild( fcn_getHtmlDropdown( 'fcn_changeEventActionType("' + evnt.actions[a].id + '", this.value );',
      [ {text: translations[3], value: 0 },
        {text: translations[4], value: 1 }
      ], null, evnt.actions[a].action ) );
      
    arParams = evnt.actions[a].param.split('|'); 
  
    switch( evnt.actions[a].action ) {
      case 0: // play tts from param
        var sParamTts = "this is a test";
        
        if( arParams.length > 0 ) {
          sParamTts = arParams[ 0 ] ;
        }
        
        const divPlayTts = document.createElement('div');
          
        const inpTts = document.createElement('input');
        inpTts.id = evnt.actions[a].id + '_par0';
        inpTts.type = "text";
        inpTts.value = sParamTts ;  
        inpTts.setAttribute('onchange', sChangeActionFcn );
        divPlayTts.appendChild( inpTts );
          
        tdActionContent.appendChild( divPlayTts );
        break;
        
      case 1: // play tts of ref image  
        const divTmp = document.createElement('div');
        divTmp.appendChild( fcn_getHtmlDropdownForImages( sChangeActionFcn, evnt.actions[a].id + '_par0', evnt.actions[a].param ) );
        tdActionContent.appendChild( divTmp );
        break;
        
      default:
        dbg( 'invalid action type "' + evnt.actions[a].event + '"' );
        break;
    }
    
    if( boDebug == true ) {
      tdActionContent.appendChild(document.createTextNode('[' + a + '] action (type ' + evnt.actions[a].action + ')' ) );
    }
  }
  
  tdEvent.appendChild( tblAction );
  
  const btnAdd = document.createElement('button'); 
  btnAdd.textContent = '+';
  btnAdd.setAttribute('onclick', 'fcn_addAction( "' + evnt.id + '" );' ); 
  
  tdEvent.appendChild( btnAdd );
  
  ref_tr.appendChild( tdEvent );
};

/* ---------------------------------------------------------------------------
 *
 */
function fcn_createCusEventsTable( oData ) {

  if( typeof oData !== 'undefined' ) {
    if( oCusEvents !== oData ) {
      if( oCusEvents !== null ) {
        oCusEvents = oData ;
        dbg( "set new cus events table" );
      }
    }
  }

  const tblDiv = document.getElementById( 'idCustomerEvents' );
  tblDiv.textContent = '';
  const tbl = document.createElement('table');
  //tbl.style.width = '100px';
  tbl.style.border = '1px solid black';
  tbl.id = 'idTblCusEvents';
  
  dbg( "create cus events table" );
  
  // assume oData is an array
  for( let i = 0; i < oCusEvents.length; i++ ) {
    const tr = tbl.insertRow();
    oCusEvents[i].id = fcn_getId();
    fcn_getHtmlForEvent( tr, oCusEvents[i], i );
  }
       
  dbg( "append cus events table" );
  
  tblDiv.appendChild( tbl );
         
  const btnAdd = document.createElement('button'); 
  btnAdd.textContent = '+';
  btnAdd.setAttribute('onclick', 'fcn_addEvent();'); 
  tblDiv.appendChild( btnAdd );
         
  const btnSubmit = document.createElement('button'); 
  btnSubmit.textContent = 'submit';
  btnSubmit.setAttribute('onclick', 'fcn_retrieveEventParam(); dbg("send data"); comm_action("cusEvents",{customerEvents:oCusEvents}, function(data){ fcn_createCusEventsTable(data.customerEvents); } );'); 
  tblDiv.appendChild( btnSubmit );       
};