<?php
echo CHtml::beginForm(url('addressbookImportExport/default/import'),'POST',array('id'=>'import-form'));
$this->widget('ext.PlGrid.PlGridView', array(
	'id'=>'csv-import-grid',
 	'headerTitle'=>'IMPORT', // optional
 	'enableAddButton'=>false,
	'enableSearchButton'=>false,
	'customButtons'=>array(
            'label'=>__('CDR_NAVBAR_BACK'),
            'url'=> $returnUrl,
            'icon'=>'arrow-left',
            'linkOptions'=>array(
                'id'=>'back_button',
                'data-target'=>'#',
                'data-translation-id'=>'CDR_NAVBAR_BACK'
            ),
        ),
	'itemsCssClass'=>'plTable items',
	'dataProvider'=>$dataProvider,
	'helpBtnUrl' => $helpBtnUrl,
	'columns'=>array(
	  array(
	      'value'=>array($this,'renderAttributesDropdown'),
	      'header'=>__('CSV_SELECT_COLUMN'),
	      'headerHtmlOptions'=>array(
		  'data-translation-id'=>'CSV_SELECT_COLUMN'
	      ),
	  ),
	  array(
	    'name'=>'attributeName',
	    'header'=>__('CSV_HEADER_COLUMN'),
	    'headerHtmlOptions'=>array(
	      'data-translation-id'=>'CSV_HEADER_COLUMN'
	    ),
	  ),
	  array(
	    'name'=>'attributeExemple_1',
	    'header'=>__('CSV_ATTRIBUTE_EXEMPLE_1_COLUMN'),
	    'headerHtmlOptions'=>array(
	      'data-translation-id'=>'CSV_ATTRIBUTE_EXEMPLE_1_COLUMN'
	    ),
	  ),
	  array(
	    'name'=>'attributeExemple_2',
	    'header'=>__('CSV_ATTRIBUTE_EXEMPLE_2_COLUMN'),
	    'headerHtmlOptions'=>array(
	      'data-translation-id'=>'CSV_ATTRIBUTE_EXEMPLE_2_COLUMN'
	    ),
	  ),
	  array(
	    'name'=>'attributeExemple_3',
	    'header'=>__('CSV_ATTRIBUTE_EXEMPLE_3_COLUMN'),
	    'headerHtmlOptions'=>array(
	      'data-translation-id'=>'CSV_ATTRIBUTE_EXEMPLE_3_COLUMN'
	    ),
	  ),
	)
    )
);
echo CHtml::hiddenField('file',$file);
echo CHtml::label(__('SKIP_FIRST_LINE_LABEL'),'skipFirstLine',array(
	'style'=>'display:inline',
	'data-translation-id'=>'SKIP_FIRST_LINE_LABEL'
    )
);
echo CHtml::checkBox('skipFirstLine','0');
echo "<br><br>";

echo "<div class='input-append input-prepend'>";
echo CHtml::button(__('CSV_IMPORT_PREVIOUS_PAGE_BUTON'),array(
      'id'=>'prevPage',
      'class'=>'btn btn-primary',
      'onclick'=>'getNewPage(this)',
      'data-currentOffset'=>$offset,
      'data-translation-id'=>'CSV_IMPORT_PREVIOUS_PAGE_BUTON',
      'data-page' => '1',
  )
);

echo CHtml::button(__('CSV_IMPORT_BUTTON'),array(
    'id'=>'submitImportForm',
    'data-translation-id'=>'CSV_IMPORT_BUTTON',
    'data-translation-target'=>'CSV_IMPORT_BUTTON_TARGET',
    'class'=>'btn btn-primary',
    ));

echo CHtml::button(__('CSV_IMPORT_NEXT_PAGE_BUTON'),array(
      'id'=>'nextPage',
      'class'=>'btn btn-primary',
      'onclick'=>'getNewPage(this)',
      'data-currentOffset'=>$offset,
      'data-translation-id'=>'CSV_IMPORT_NEXT_PAGE_BUTON',
      'data-page' => '4',
  )
);
echo "</div>";
echo CHtml::dropDownList('encodingStandard','utf8',array('utf8'=>'UTF-8','iso-8859-1'=>'ISO-8859-1','iso-8859-15'=>'ISO-8859-15'),array('data-page'=>'1'));


echo CHtml::endForm();

$this->beginWidget('bootstrap.widgets.TbModal', array(
    'options'=>array(
	'backdrop'=>'static'
      ),
      'htmlOptions'=>array(
	  'id'=>'progressModal')
      )
);
?>
<div class="modal-header" >
    <a class="close" data-dismiss="modal">&times;</a>
    <h3 id="progressBarModalHeader"><?php echo __('PROGRESS_BAR_HEADER_PROCESS'); ?></h3>
    <h3 id="progressBarModalHeaderSuccess" style="display:none"><?php echo __('PROGRESS_BAR_HEADER_SUCCESS'); ?></h3>
</div>
<div class="modal-body" id="progressBarModalBody">
    <?php 
	    $this->widget('bootstrap.widgets.TbProgress', array(
	    		'type'=>'info', // 'info', 'success' or 'danger'
	    		'percent'=>0, // the progress
	    		'striped'=>true,
	    		'animated'=>true,
	    		'htmlOptions'=>array('id'=>'progressBar')
	    ));
    ?>
</div>
 
<div class="modal-footer">
    <?php $this->widget('bootstrap.widgets.TbButton', array(
    	'id'=>'btnAbort',
        'label'=>__('CSV_IMPORT_ABORT_BUTTON'),
    	'type'=>'danger',
        'url'=>'#',
        'loadingText'=>__('GLOBAL_LOADING_TEXT'),
        'htmlOptions'=>array(
			'onclick'=>'cancel(this)'	
        ),
    )); 
    $this->widget('bootstrap.widgets.TbButton', array(
    	'id'=>'btnOK',
        'label'=>__('CSV_IMPORT_SUCCESS_BUTTON'),
        'loadingText'=>__('GLOBAL_LOADING_TEXT'),
    	'type'=>'success',
        'url'=>'#',
        'htmlOptions'=>array(
			'style'=>"display:none",
			'onclick'=>'followTheReturnUrl(this)'

	),
    )); 
?>
</div>
<?php
$this->endWidget();

?>

<script>
// global variables :
    var caneled = false;
    
$('#submitImportForm').on('click',function() {
    var limit = 6144;
    var fileSize = <?php echo $_FILES['file']['size'] ?>;

    var someValueWasSelected = false;
    var selects = {};
    var fileName = $('#file').val();
    var delimiter = $('#delimiter').val();
    $('#import-form').find('select:not(#encodingStandard)').each(function(i,el){
	  
	  var key = $(el).attr('id');
	  var value = $(el).val();
	  if (!someValueWasSelected && value != "") {
	    someValueWasSelected = true;
	  } 
	  selects[key]= value;
    }); 
    var params = '<?php echo json_encode($params); ?>';
        
    if (!someValueWasSelected) {
      alert( '<?php echo __('CSV_IMPORT_NO_SELECT_VALUES_FOUND'); ?>' );
      return false;
    }
    $.post(
      '<?php  echo url('addressbookImportExport/default/import'); ?>',
      {
	sort:selects,
 	fileSize:fileSize,
	limit:limit,
	offset:'0',
	fileName: fileName,
	delimiter:delimiter,
	params:params,
	encoding:$('#encodingStandard').val(),
	model: '<?php echo $model; ?>',
	skipFirstLine: $('#skipFirstLine').is(':checked'),
	'<?php echo Yii::app()->request->csrfTokenName; ?>':'<?php echo Yii::app()->request->csrfToken; ?>',
      },
      function(data) {
      
	$('#progressModal').modal('show');
      
	if (!data.eof) {
	
	    importData(data);
	    setProgressbarValue(calculateProgress(data.offset, data.fileSize));
	  } else {
	  
	    clearTempDir(data.fileName);
	    $("#progressBar .bar").width(0+"%");
	    $(".modal-body").html('<div class="alert alert-block alert-success">'+'<?php echo __("CSV_IMPORT_SUCCESS_MESSAGE"); ?>'+'</div>');
	    
	    
	    $('#progressBarModalHeader').hide();
	    $('#progressBarModalHeaderSuccess').show(); 
	    
	    $('.modal-footer').find('.btn-danger').hide();
	    $('.modal-footer').find('.btn-success').show();
	  }
      },
      'json'
    ).error(function(q,w,e){
	console.log(q);
	console.log(w);
	console.log(e);
    });
    return false;
});

function importData(data) {
    $.post(
      '<?php  echo url('addressbookImportExport/default/import'); ?>',
      {
	sort:data.sort,
	fileSize:data.fileSize,
	limit:data.limit,
	offset:data.offset,
	fileName: data.fileName,
	delimiter:data.delimiter,
	model: data.model,
	params:data.params,
	encoding:data.encoding,
	skipFirstLine: data.skipFirstLine,
	'<?php echo Yii::app()->request->csrfTokenName; ?>':'<?php echo Yii::app()->request->csrfToken; ?>',
      },
      function(data) {
      
	  if (!caneled) {
	      if (!data.eof) {
		importData(data);
		setProgressbarValue(calculateProgress(data.offset, data.fileSize));
	      } else {
		clearTempDir(data.fileName);
		$("#progressBar .bar").width(0+"%");
		$(".modal-body").html('<div class="alert alert-block alert-success">'+'<?php echo __("CSV_IMPORT_SUCCESS_MESSAGE"); ?>'+'</div>');
		
		
		$('#progressBarModalHeader').hide();
		$('#progressBarModalHeaderSuccess').show(); 
		
		$('.modal-footer').find('.btn-danger').hide();
		$('.modal-footer').find('.btn-success').show();
	      } 
	  } else {
// if you implement dis read importedIds from a File
// 	      data.currentProgressState = calculateProgress(data.offset, data.fileSize)-1;
// 	      data.currentProgress = data.currentProgressState;
// 	      data.offset = 0;
// 	      data.newIdCount = data.importedIds.length;
	  } 
      },
      'json'
    ).error(function(q,w,e){
	console.log(q);
	console.log(w);
	console.log(e);
    });  
}

function cancel(btn) {
    caneled = true;
    var btn = $(btn);

    btn.button('loading');
     window.location = '<?php echo $returnUrl;?>';
}

function deleteimportedData(data) {
  setProgressbarValue(Math.round(data.currentProgress));
  $.post(
    '<?php echo url('addressbookImportExport/default/ajaxCancelImport') ?>',
    {
      '<?php echo Yii::app()->request->csrfTokenName; ?>':'<?php echo Yii::app()->request->csrfToken; ?>',
      importedIds:data.importedIds,
      idCount:data.importedIds.length,
      offset:data.offset,
      model:data.model,
      newIdCount:data.newIdCount,
      currentProgress:data.currentProgress,
      currentProgressState:data.currentProgressState
    },
    function(data) {
      if (data.newIdCount > 0) {
	deleteimportedData(data)
      } else {
	caneled = false;

	$('#progressModal').modal('hide');
      }
    },
    'json'
  );
}

function setProgressbarValue(progress) {
	$("#progressBar .bar").width(progress+"%");
	$("#progressBar > div").text(progress+"%");
}
function calculateProgress(offset, count){
	var progress = (offset/count)*100;
	return Math.round(progress);
}

function clearTempDir(fileName) {
  $.post(
    '<?php echo url('addressbookImportExport/default/ajaxClearTempFolder');?>',
    {
      '<?php echo Yii::app()->request->csrfTokenName; ?>':'<?php echo Yii::app()->request->csrfToken; ?>',
      fileName:fileName
    },
    function(){},
    'json'
  );
}

function followTheReturnUrl(btn) {

    var btn = $(btn);
    btn.button('loading');
    window.location = '<?php echo $returnUrl;?>';
}


// pagination  : 
function getNewPage(element) {
  
  var fileName = $('#file').val();
  var oldPage = $(element).attr('data-page');
  var url = '<?php echo url('addressbookImportExport/default/ajaxGetNextPreviewPage');?>';
  var pageSize = 6;
  $.post(
  url,
  {
    '<?php echo Yii::app()->request->csrfTokenName; ?>':'<?php echo Yii::app()->request->csrfToken; ?>',
    offset:$(element).attr('data-currentOffset'),
    encoding:$('#encodingStandard').val(),
    page:$(element).attr('data-page'),
    fileName:fileName,
  },
  function(data) {
	if (element.id == 'nextPage') {
	  if (oldPage-3 < 1) {
	    oldPage = 4;
	  }
	  if (data.page != oldPage) {
	    $('#prevPage').attr('data-page',(oldPage-3));
	  }
	  $(element).attr('data-page',data.page);
	} else {
	  if (oldPage < 4) {
	    oldPage = 4;
	  }
	  if (data.page-pageSize < 1) {
	      $(element).attr('data-page',1);
	  }else {
	  $(element).attr('data-page',(data.page-pageSize));
	  }
	  $('#nextPage').attr('data-page',oldPage);
	} 
	
	$('#encodingStandard').attr('data-page',data.currentPage);
 	fillPreviewTable(data.data);
  },
  'json'
  );
}
$('#encodingStandard').change(function() {
  
  getNewPage($('#encodingStandard'));
});

function fillPreviewTable(data){
  $.each(data[0],function(index,element){
    if ($('#'+index)) {
      $('#'+index).parent().next().text(element);
    }
  });
    $.each(data[1],function(index,element){
    if ($('#'+index)) {
      $('#'+index).parent().next().next().text(element);
    }
  });
  $.each(data[2],function(index,element){
    if ($('#'+index)) {
      $('#'+index).parent().next().next().next().text(element);
    }
  });
  $.each(data[3],function(index,element){
    if ($('#'+index)) {
      $('#'+index).parent().next().next().next().next().text(element);
    }
  });
}
</script>