//*******************************************************
// Extension BO module
//*******************************************************

//Prepare csv tobacco data save into invibit server **************************
var filenameBC      = '';
var filenameDA      = '';
var blobTobacco     = '';
var csvUrlTobacco   = '';
var BarcodeData     = '';
var DescriptionData = '';
var TobaccoData     = 'var Tobacco = {\r\n';
  
function PrepareTobaco()
{
  filenameBC      = '';
  filenameDA      = '';
  blobTobacco     = '';
  csvUrlTobacco   = '';
  BarcodeData     = '';
  DescriptionData = '';
  TobaccoData     = 'var Tobacco = {\r\n';
  
  var out = '';
  out += '<div class="ctlframe grad_white ctlframe2">';
  out +=   '<table id="csvTOctls" style="width:99%; margin-left:10px;">';
  out +=     '<tr><td colspan="2"><hr/></td></tr>';
  out +=     '<tr style="text-align:center; vertical-align:middle; text-align:center;">';
  out +=       '<td style="width:140px">';
  out +=         '<div id="fscontBCcsv" class="btn" style="width:120px;">'+msg.x49_Choose_BC_file+'</div>';
  out +=         '<input id="fselBCcsv" type="file" style="width:1px; height:1px; overflow:hidden; display:none;" accept="*.csv"></input>';
  out +=       '</td>';
  out +=       '<td>';
  out +=         '<input class="in_txt" id="fnameBCcsv" type="text" readonly style="width:100%; height:30px; color:gray;"></input>';
  out +=       '</td>';
  out +=     '</tr>';
  out +=     '<tr style="text-align:center; vertical-align:middle; text-align:center;">';
  out +=       '<td style="width:140px">';
  out +=         '<div id="fscontDAcsv" class="btn" style="width:120px;">'+msg.x49_Choose_DA_file+'</div>';
  out +=         '<input id="fselDAcsv" type="file" style="width:1px; height:1px; overflow:hidden; display:none;" accept="*.csv"></input>';
  out +=       '</td>';
  out +=       '<td>';
  out +=         '<input class="in_txt" id="fnameDAcsv" type="text" readonly style="width:100%; height:30px; color:gray;"></input>';
  out +=       '</td>';
  out +=     '</tr>';
  out +=     '<tr><td colspan="2"><hr/></td></tr>';

  out +=     '<tr style="text-align:center; vertical-align:middle; text-align:center;">';
  out +=      '<td id="exportcontjsonp">';
  out +=        '<a style="color:black;" id="exportjsonp" href="" download="" name="" title="'+msg.x31_Download_TobaccoData+'">';
  out +=          '<table class="btn"><tr>';
  out +=            '<td style="width:85px; height:18px; text-align:center;"><span style="width:22px;" class="wicons pvico_save"></span></td>';
  out +=            '<td>'+msg.x31_JSON_save+'</td>';
  out +=            '<td style="width:4px;">';
  out +=          '</tr></table>';  
  out +=        '</a>';
  out +=      '</td>';
  out +=     '</tr>';
  out +=   '</table>';
  out += '</div>';
  
  $('#datacontent').html(out);

  $('#exportcontjsonp').hide();

  $('#exportcontjsonp').bind(clickevent(), function() { $('#exportcontjsonp').hide(); });
  $('#fscontBCcsv').bind(clickevent(), function() { $('#fselBCcsv').val(''); $('#fselBCcsv').click(); });
  $('#fselBCcsv').bind("change", function() {
    BarcodeData = '';
    var blob = this.files[0];
    filenameBC = $('#fselBCcsv').val();
    $('#fnameBCcsv').val(filenameBC);
    if(!filenameBC.length) return;
    var reader = new FileReader();
    reader.onload = function(e) {
      loading_hide();
      var response = reader.result.replace(/[\r\n]+/g,"~");
      var splitlines = response.split('~');
      if(splitlines < 2) { err(msg.x42_Not_found_Barcode_data, function() {topmenu(-10); } ); return; }
      
      var fieldsep = (cfg[0].csvdelimiter === 0? ';' : ',');
      var BCheader = splitlines[0].split(fieldsep);
      if(BCheader.length != 2) { err(msg.x42_Not_found_Barcode_data, function() {topmenu(-10); } ); return; }
      if(BCheader[0] != 'CODE' || BCheader[1] != 'BARCODE') { err(msg.x42_Not_found_Barcode_data, function() {topmenu(-10); } ); return; }
      
      BarcodeData+= 'barcode:"';
      BarcodeData+=escape(reader.result)+'"';
      
      if(DescriptionData != '') {
        TobaccoData     = 'var Tobacco = {\r\n';
        TobaccoData+='DATE:"'+get_date_str(1)+'",\r\n';
        TobaccoData+=BarcodeData+',\r\n';
        TobaccoData+=DescriptionData+'};\r\n';
        blobTobacco    = new Blob([TobaccoData], { type:'text/csv' });
        csvUrlTobacco  = URL.createObjectURL(blobTobacco);
        $('#exportjsonp').attr({'href':csvUrlTobacco, 'name':'Tobacco.jsonp', 'download':'Tobacco.jsonp' });
        $('#exportcontjsonp').show();
      }
      
    }
    reader.onerror = function(e) {
      loading_hide();
      err(msg.x47_load_failed);
    }
    loading_show(msg.x27_Please_wait);
    reader.readAsText(blob, "utf-8");
  });

  $('#fscontDAcsv').bind(clickevent(), function() { $('#fselDAcsv').val(''); $('#fselDAcsv').click(); });
  $('#fselDAcsv').bind("change", function() {
    DescriptionData = ''
    var blob = this.files[0];
    var filenameDA = $('#fselDAcsv').val();
    $('#fnameDAcsv').val(filenameDA);
    if(!filenameDA.length) return;
    var reader = new FileReader();
    reader.onload = function(e) {
      loading_hide();

      var response = reader.result.replace(/[\r\n]+/g,"~");
      var splitlines = response.split('~');
      if(splitlines < 2) { err(msg.x42_Not_found_Tobacco_data, function() {topmenu(-10); } ); return; }
      
      var fieldsep = (cfg[0].csvdelimiter === 0? ';' : ',');
      var BCheader = splitlines[0].split(fieldsep);
      if(BCheader.length != 4) { err(msg.x42_Not_found_Tobacco_data, function() {topmenu(-10); } ); return; }
      
      if(BCheader[0] != 'CODE' || BCheader[1] != 'DESCRIPTION' || BCheader[2] != 'PRICE' || BCheader[3] != 'AAMS') { 
        err(msg.x42_Not_found_Tobacco_data, function() {topmenu(-10); } ); return; 
      }


      DescriptionData+= 'description:"';
      DescriptionData+=escape(reader.result)+'"';
      
      
      
      
      
      
      
      if(BarcodeData != '') {
        TobaccoData     = 'var Tobacco = {\r\n';
        TobaccoData+='DATE:"'+get_date_str(1)+'",\r\n';
        TobaccoData+=BarcodeData+',\r\n';
        TobaccoData+=DescriptionData+'};\r\n';  
        blobTobacco    = new Blob([TobaccoData], { type:'text/csv' });
        csvUrlTobacco  = URL.createObjectURL(blobTobacco);
        $('#exportjsonp').attr({'href':csvUrlTobacco, 'name':'Tobacco.jsonp', 'download':'Tobacco.jsonp' });
        
        $('#exportcontjsonp').show();
      }
    }
    reader.onerror = function(e) {
      loading_hide();
      err(msg.x47_load_failed);
    }
    loading_show(msg.x27_Please_wait);
    reader.readAsText(blob, "utf-8");
  });
}
//============================================================================


////////////////////// A string identifying your extension (will be made visible with a key)
var x31_reprint_receipt                                   = 'Reprint Receipr from ECR';
var x31_reprint_invoice                                   = 'Reprint Invoice from ECR';
var x31_invalid_data                                      = 'Invalid data';
var devlistindices = [];
var Reptypestartdate    = null;
var saveReptype         = -1;
var ecrselected         = -1;
var SelectDate          = '';
var ecrdevlist_indices  = [];                     // Reset device indices
var ecrdevlist_names    = [];

var _ext_info       = "My Back Office Module, v1.00a, 20-01-2017";
var _ext_menu_descr = "My Menu"; 
var _ext_menu_help  = "This is my menu for more functions";
var _ext_menu_ico   = "m_tools";

var PRNStyle = { NORMAL:0, DOUBLEHEIGHT:1, DOUBLEWIDTH:2, EMPHASIZED:4, WHITEBLACK:8 };

// Only whit this parameter work OK "WHITEBLACK" style
var WHITEBLACK_A  = PRNStyle.NORMAL       | PRNStyle.WHITEBLACK;
var WHITEBLACK_B  = PRNStyle.DOUBLEHEIGHT | PRNStyle.WHITEBLACK;

////////////////////// Array of custom keys (available in front office keyb config)
var _ext_keys = [
/// id:Unique String, text:Button Text, callback:Name and parameters for function to call, image:use same for all for now,  idicon:use same for all for now
  { id:'extkb1', text:'Custom Report', callback:"ext_make_report",       help:'This is external function',    image:"selico_items", idicon:'_icon' },
  { id:'extkb2', text:'FP commands',   callback:"ext_send_commands_fp",  help:'This is my function',          image:"selico_items", idicon:'_icon' },
  { id:'extkb3', text:'Reprint REC',   callback:"ReprintECRRec",         help:'Reprint from ECR RECEIPT',     image:"selico_items", idicon:'_icon' },
  { id:'extkb4', text:'Reprint INV',   callback:"ReprintECRInv",         help:'Reprint from ECR INVOICE',     image:"selico_items", idicon:'_icon' },
  { id:'extkb5', text:'Update Tobacco',callback:"PrepareTobaco",         help:'This is information function', image:"selico_items", idicon:'_icon' },
  { id:'extkb6', text:'Info',          callback:"ext_info",              help:'This is information function', image:"selico_items", idicon:'_icon' }
];

function begin_report()                   { user_report_data = [];                                                     }
function add_report_line(actstyle, data)  { user_report_data += actstyle+data+'\r\n';                                  }
function add_feed_cut()                   { user_report_data += '0!~0\r\n';                                            }
function prn_report()                     { var mode = 1; print_user_report('?m='+mode+'&t= Demo report&r=7', user_report_data); }

//Request URL:http://127.0.0.1/userreport.js?m=0&t=%20&r=7
//Request URL:http://127.0.0.1/userreport.js?m=1&t=%20Sales%20statistics%20report&r=7
////////////////////// Custom functions
function ext_make_report()
{
  msgbox("Customer Report", '', '<b>Press OK</b>', function(){  
    begin_report();
    add_report_line(PRNStyle.NORMAL,                      'Printing NORMAL style data');
    add_report_line(PRNStyle.NORMAL|PRNStyle.EMPHASIZED,  'Printing NORMAL & EMPHASIZED style data');
    add_report_line(PRNStyle.DOUBLEHEIGHT,                'Printing DOUBLEHEIGHT style data');
    add_report_line(PRNStyle.DOUBLEWIDTH,                 'Printing DOUBLEWIDTH style data');
    add_report_line(WHITEBLACK_A,                         'Printing WHITEBLACK_A style data');
    prn_report();
  });
}

function ext_info()
{
  msgbox("Extension info", '', '<b>Extension information:</b><br>'+_ext_info);
}

//******************************************************
// Start batch upload
//******************************************************
function Find_FP_dev()                                                  // Find fiscal ecr devices
{
  devlistindices      = [];
  ecrdevlist_indices  = [];                     // Reset device indices
  ecrdevlist_names    = [];
  for(var i=0; i<db_dev.length; i++) {
    if(db_dev[i].flags.charAt(0) != '1')  continue;                     // This device is deleted
    if(db_dev[i].cls != 4)                continue;                     // Filter EFD/FP devices only
    if(db_dev[i].conntype == 3)           continue;                     // This device is inactive
    
    devlistindices.push(i);                                             // Ok found FP device
    ecrdevlist_indices.push(i);
    ecrdevlist_names.push(db_dev[i].name);
  }
  if(devlistindices.length) return(devlistindices[0]); else return(-1); // if found device return 1st device else return -1(Not found)
}


function do_efd_commands()
{
  if(EFD.selected_dev == -1) { err("No device selected.."); return; }

  EFD.curline = 0;
  EFD.aborted = 0;

  var nextRequest = function() 
  {
    
    if(EFD.aborted) {  err('Response [ (Aborted) ]'); return;  }
    if(EFD.curline >= EFD.commands.length)            return;
    var req = EFD.commands[EFD.curline++];
    if(req.length == 0) { nextRequest();              return; }
    console.log('Send req=>['+req+']');
    fp_raw_request(req, 
      function(res) {
        if(EFD.aborted) { msgbox('Command ['+req+']', '', 'Response [ (Aborted) ]', function() { return; } ); return; }
        if(res == null) res = '-';
        nextRequest();
        //msgbox('Command ['+req+']', '', 'Response ['+res+']', function() { nextRequest(); } );
      }, 
      function() {
        if(EFD.aborted) { msgbox('Command ['+req+']', '', 'Response [ ABORTED]', function() { return; } ); return; }
        var errmsg = '';
        nextRequest();
        /*
        if(FP.response.err != undefined && FP.response.err != null) errmsg += FP.response.err;
        if(FP.response.neterr != undefined && FP.response.neterr != null) errmsg += '-' + FP.response.neterr;
        msgbox('Command ['+req+']', '', 'Response ['+errmsg+']', function() { nextRequest(); } );
        */
      },
      function() {
        EFD.aborted = 1;
      }
    );
  }
  nextRequest();
}

function begin_fp(ecrdev) 
{
  var dev = Find_FP_dev();
  
  EFD.selected_dev = dev;
  if(ecrdev != undefined) {
    EFD.selected_dev = -1;
    if(devlistindices.length) {
      if(devlistindices.indexOf(ecrdev) > -1) EFD.selected_dev = ecrdev;
    }  
  }
  EFD.text          = '';
  EFD.commands      = [];
  return(EFD.selected_dev);
}

function add_fp_commnd(command)
{
  if(EFD.selected_dev == -1) return;  // Dont select valis device
  EFD.commands.push(command);
}

function ext_send_commands_fp()
{
  if(begin_fp() == -1) { err('Not found FP device'); return; }                    //Not found FP device for request
  add_fp_commnd('=c');
  add_fp_commnd('=K');
  add_fp_commnd('=o');
  add_fp_commnd('="/( 1this is reportt 1 )');
  add_fp_commnd('="/( 2this is reportt 2 )');
  add_fp_commnd('="/( 3this is reportt 3 )');
  add_fp_commnd('="/( 4this is reportt 4 )');
  add_fp_commnd('="/( 5this is reportt 5 )');
  add_fp_commnd('=c');  
  do_efd_commands();
}

  function SelectActiveEcr()
  {
    var selector = ecrdevlist_indices.indexOf(ecrselected);
    select_table(msg.x49_Select_terminal, ecrdevlist_names, null, selector, 620, 
      function(sel) { 
        ecrselected = ecrdevlist_indices[sel];
        $('#selecr').text(db_dev[ecrselected].name); 
        ReprintECR(saveReptype);
      }, 
      0, 
      function() {}
    );
  }
  function ReprintECRRec() { ReprintECR(0); }
  function ReprintECRInv() { ReprintECR(1); }
  
  function ReprintECR(Reptype)  // 0=RECEIPT 1=INVOICE
  {
    Find_FP_dev();
    if(ecrdevlist_indices.length == 0) { err(msg.x49_err_No_EFD_devices_defined); return; }
    if(ecrselected == -1) ecrselected = ecrdevlist_indices[0];
    
    if(Reptypestartdate == null)  { 
      Reptypestartdate  = new Date();
      SelectDate = date2strddmmyy(Reptypestartdate);
    }
    if(saveReptype == -1)         saveReptype       = Reptype;
    var out = '';
    var headertxt = x31_reprint_receipt;
    if(Reptype == 1) headertxt = x31_reprint_invoice;
    if(ecrselected != -1) headertxt+=' "'+db_dev[ecrselected].name+'"';
    ///// Header
    out  = '<table style="margin-top:5px;border-spacing:6px;">';
    out +=    '<tr>';
    out +=       '<td class="dlgtitle dlgbutton_rel" id="selecr" style="width:99%; font-weight:bold; vertical-align:middle; text-align:center;">'+headertxt+'</td>';
    out +=       '<td class="dlgbutton dlgbutton_release" id="repexit" style="color:rgb(130,0,0);">&nbsp;X&nbsp;</td>';
    out +=    '</tr>';  
    out += '</table><hr/>';
    out += '<table style="width:100%; font-size:14px; font-weight:normal;">';
    
    out +=   '<tr style="height:34px;">';
    out +=    '<td style="width:15%; text-align:right;">'+ msg.x55_Repdata_date+'&nbsp;</td>';
    out +=    '<td style="width:25%"><input id="repdata"  type="text" class="textin" style="width:200px;"  maxlength="16">&nbsp;&nbsp;</td>';
    out +=   '</tr>';
    
    out +=   '<tr style="height:34px;">';
    out +=     '<td style="width:15%; text-align:right;">' + msg.x10_From+'&nbsp;</td>';
    out +=     '<td style="width:25%"><input id="repfrom"  type="text" class="textin" style="width:200px;"  maxlength="20">&nbsp;&nbsp;</td>';
    out +=   '</tr>';

    out +=   '<tr id="allfldto" style="height:34px;">';
    out +=     '<td style="width:15%; text-align:right;">' + msg.x10_to+'&nbsp;</td>';
    out +=     '<td style="width:25%"><input id="repto"  type="text" class="textin" style="width:200px;"  maxlength="20">&nbsp;&nbsp;</td>';
    out +=   '</tr>';
    
    out += '</table>';
    //////// FOOTER
    out += '<hr/>';
    out += '<table style="width:100%; height:42px;"><tr>';
    out +=   '<td></td>';
    out +=   '<td style="text-align:center;"><button id="repsend"  style="width:92px; height:32px; font:bold 15px helvetica; color:rgb(122,122,122);">'+msg.x1_Done + '</button></td>';
    out +=   '<td></td>';
    out += '</tr></table>';
    
	  popup(out, 550);
	  dialog_show_hide(1);  // 1->show 0->hide
    
    if(Reptype==1) $('#allfldto').hide();
    
    $('#repdata').val(date2str(Reptypestartdate));
    $('#repdata').html(date2str(Reptypestartdate));

    $('#repdata').unbind();
    $('#repdata').bind(clickevent(), function() {
      set_range();
    });  
    
    $('repexit').unbind();
    $('#repexit').bind(clickevent(), function() {
      hide_dialog(0);
      Reptypestartdate  = null;
      saveReptype       = -1;
    }); 
    
    $('repfrom').unbind();
    $('#repfrom').bind(clickevent(), function() {
      $('#repfrom').focus();
    }); 

    $('repto').unbind();
    $('#repto').bind(clickevent(), function() {
      $('#repto').focus();
    }); 
    
    $('selecr').unbind();
    $('#selecr').bind(clickevent(), function() {
      SelectActiveEcr();
    }); 

    $('repsend').unbind();
    $('#repsend').bind(clickevent(), function() {
      var from = 0;
      var to   = 0;
      if(Reptype==0) {
        from = $('#repfrom').val();         
        to   = $('#repto').val();
        if(!isNumeric(from) || !isNumeric(to))  { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
        if(from == to && from == 0)             { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
        if(from > to)                           { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
      } else {
        from = $('#repfrom').val();         
        if(!isNumeric(from) )                   { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
        if(from == 0)                           { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
      }
      begin_fp(ecrselected);
      var command = '';
      command = '=C3';
      add_fp_commnd(command);
      if(Reptype==0) {  // command for receipt
        command = '=C452/$1/&'+SelectDate+'/['+from+'/]'+to;
      } else {          // command for invoice
        command = '=C454/$1/&'+SelectDate+'/['+from;
      }
      add_fp_commnd(outpatch(command));
      do_efd_commands();
    }); 
}

function set_range()
{
  scroller_params.preset = 'date';
  Set_Scroller_format(scroller_params, 'full');
  delete scroller_params.wheels;
  input_scroller(300, msg.x44_Select_Date+'..', null,
    function(arr) { 
      Reptypestartdate = new Date(arr[2], arr[1], arr[0]);
      SelectDate = date2strddmmyy(Reptypestartdate);
      $('#repdata').val(date2str(Reptypestartdate));
      $('#repdata').html(date2str(Reptypestartdate));
      ReprintECR(saveReptype);
    },
    null, scroller_params
  );
  $('#scroller').scroller('setDate', Reptypestartdate, true);
}

function date2strddmmyy(date)
{
  var m, out = "";
  m = date.getDate().toString();      if(m.length == 1) m = '0' + m;  out += m;
  m = (date.getMonth()+1).toString(); if(m.length == 1) m = '0' + m;  out += m;
  m = date.getFullYear().toString(); 
  var yy = m.substring(2, 4);
  out += yy;
  return(out);
}
