jQuery(document).ready(function($) {

    const { __, _x, _n, sprintf } = wp.i18n;
    //var textoNombre = objeditor.textoNombre;
    var textoNombre = objeditor.textoNombre;
    var textoValoracion = objeditor.textoValoracion;
    var textoReviews = objeditor.textoReviews;
    var textoDireccion = objeditor.textoDireccion;
    var textoMunicipio = objeditor.textoMunicipio;
    var textoProvincia = objeditor.textoProvincia;
    var textoCodigoPostal = objeditor.textoCodigoPostal;
    var textoPais = objeditor.textoPais;
    var textoWebsite = objeditor.textoWebsite;
    var textoTelefono = objeditor.textoTelefono;
    var textoHorario = objeditor.textoHorario;
    var textoLatitud = objeditor.textoLatitud;
    var textoLongitud = objeditor.textoLongitud;
    var textoImagen = objeditor.textoImagen;
    var textoImagenes = objeditor.textoImagenes;
    var textoCategoriaPadre = objeditor.textoCategoriaPadre;
    var textoCategoria = objeditor.textoCategoria;
    var textoEtiqueta = objeditor.textoEtiqueta;
    var textoTitulo = objeditor.textoTitulo;
    var textoMigaPan = objeditor.textoMigaPan;
    var textoLunes = objeditor.textoLunes;
    var textoMartes = objeditor.textoMartes;
    var textoMiercoles = objeditor.textoMiercoles;
    var textoJueves = objeditor.textoJueves;
    var textoViernes = objeditor.textoViernes;
    var textoSabado = objeditor.textoSabado;
    var textoDomingo = objeditor.textoDomingo; 
    var anadir = objeditor.anadir;
    var editar = objeditor.editar;
    var borrar = objeditor.borrar;
    var csv = objeditor.csv;
    //var arreglos = objeditor.arreglos;
    var columns = [
        {
        data: "id",
        title: "Id",
        //type: "readonly",
	visible: false
        },
         {
        data: "GMapsLink",
        title: "Link"
        },
 	 {
        data: "OrganizationName",
        title: textoNombre
        },
         {
        data: "RateStars",
        title: textoValoracion
        },
        {
        data: "ReviewsTotalCount",
        title: textoReviews
        },
		{
        data: "OrganizationAddress",
        title: textoDireccion
        },
	{
        data: "municipio",
        title: textoMunicipio
        },
	{
        data: "provincia",
        title: textoProvincia
        },
	{
        data: "cp",
        title: textoCodigoPostal
        },
	{
        data: "pais",
        title: textoPais
        },
	{
        data: "OrganizationWebsite",
        title: textoWebsite
        },
	{
        data: "OrganizationPhoneNr",
        title: textoTelefono
        },
		{
        data: "OrganizationWorkTime",
        title: textoHorario
        },
	{
        data: "OrganizationLatitude",
        title: textoLatitud
        },
	{
        data: "OrganizationLongitude",
        title: textoLongitud
        },
	{
        data: "OrganizationHeadPhotoURL",
        title: textoImagen
        },
        {
        data: "OrganizationPhotosURLs",
        title: textoImagenes
        },
  	{
        data: "OrganizationEmail",
        title: "Email"
        },
        {
        data: "ShareLink",
        title: "ShareLink"
        },
        {
        data: "categoriapadre",
        title: textoCategoriaPadre
        },
        {
        data: "SearchRequest",
        title: textoCategoria
        },
  	{
        data: "etiqueta",
        title: textoEtiqueta
        },
        {
        data: "EmbedMapCode",
        title: "Iframe"
        },
        {
        data: "metatitle",
        title: "Meta Title"
        },
          {
        data: "metadesc",
        title: "Meta Description"
        },
          {
        data: "h1",
        title: textoTitulo
        },
          {
        data: "slug",
        title: "Slug"
        },
          {
        data: "migapan",
        title: textoMigaPan
        },
          {
        data: "lunes",
        title: textoLunes
        },
          {
        data: "martes",
        title: textoMartes
        },
          {
        data: "miercoles",
        title: textoMiercoles
        },
          {
        data: "jueves",
        title: textoJueves
        },
                 {
        data: "viernes",
        title: textoViernes
        },
          {
        data: "sabado",
        title: textoSabado
        },
          {
        data: "domingo",
        title: textoDomingo
        },
          {
        data: "var1",
        title: "Var1"
        },
          {
        data: "var2",
        title: "Var2"
        },
          {
        data: "var3",
        title: "Var3"
        },
          {
        data: "var4",
        title: "Var4"
        },
          {
        data: "var5",
        title: "Var5"
        },
          {
        data: "var6",
        title: "Var6"
        },
          {
        data: "var7",
        title: "Var7"
        },
          {
        data: "var8",
        title: "Var8"
        },
          {
        data: "var9",
        title: "Var9"
        },
          {
        data: "var10",
        title: "Var10"
        },
		 {
        data: "gmapsid",
        title: "Maps ID"
        },
		 {
        data: "keyword",
        title: "Keyword"
        },
        {
        data: "escrapeo",
        title: "Escrapeo"
        },
    ];

    var myTable;


    myTable = $('#nichetabla').DataTable({
		lengthMenu: [
        [50, 100, 500, -1],
        [50, 100, 500, 'All']
    ],
        "sPaginationType": "full_numbers",
        initComplete: function (oSettings, json) {
        // hide empty columns
        //hideEmptyColumns(this);
          //var table = this;
		  let table = this.api();
			setTimeout(function () {
			hideEmptyColumns('#nichetabla');
			}, 50);
    },
          ajax: {
            //url : url_ws_mock_get,
			url: objeditor.ajaxurl,
			method: 'POST',
			dataType: 'json',
			data: {
			action: 'lanzar_editor',
			type:'load',
			nonce: objeditor.nonce,
			},
            // our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
            dataSrc : ''
        }, 
        columns: columns,
        dom: 'Bfrtipl',        // Needs button container
        //select: 'single',
        select: 'multi',
        //responsive: true,
        altEditor: true,     // Enable altEditor
		//fixedHeader: true,
		scrollX: true,
		scrollY: '70vh',
		scrollCollapse: true,
       buttons: [
            {
                text: anadir,
                name: 'add'        // do not change name
            },
            {
                extend: 'selected', // Bind to Selected row
                text: editar,
                name: 'edit'        // do not change name
            },
            {
                extend: 'selected', // Bind to Selected row
                text: borrar,
                name: 'delete'      // do not change name
            },
			{
			text: csv,
			name:'csv',
			action: download
			},
			 {
                        text: 'Arreglos',  // El texto del botón
                        action: function ( e, dt, node, config ) {
                            window.location.href = '/wp-admin/admin.php?page=nichecreator_limpieza'; 
                        }
                    },
        ], 
        onAddRow: function(datatable, rowdata, success, error) {
            $.ajax({
                // a tipycal url would be / with type='PUT'
                url: objeditor.ajaxurl,
				method: 'POST',
				dataType: 'json',
				//type: 'post',
                data: {
					action: 'lanzar_editor',
					rowdata:rowdata,
					type:'add',
					nonce: objeditor.nonce,
					},
                success: success,
                error: error
            });
        },
        onDeleteRow: function(datatable, rowdata, success, error) {
            $.ajax({
                // a tipycal url would be /{id} with type='DELETE'
                url:objeditor.ajaxurl,
                method: 'POST',
                dataType: 'json',
                //contentType: 'application/json',
                data: {
					action: 'lanzar_editor',
					rowdata:rowdata,
					type:'delete',
					nonce: objeditor.nonce,
					},
// 		 data: rowdata,
             success: success,
                error: error
            });
        },
        onEditRow: function(datatable, rowdata, success, error) {
            $.ajax({
                // a tipycal url would be /{id} with type='POST'
                //url: url_ws_mock_ok,
				url:objeditor.ajaxurl,
                method: 'POST',
				dataType: 'json',
                data: {
					action:'lanzar_editor',
					rowdata:rowdata,
					type:'edit',
					nonce: objeditor.nonce
					},
                success: success,
                error: error
            });
        }
    });

});

/*
 * check all cells of given datatable and hide each column containing only empty cells
 * ATTENTION: this will only work if responsive-property in datatables is set to true
 */
 
function hideEmptyColumns(selector) {
    var table = jQuery(selector).DataTable();
    var totalColumns = table.columns().header().length;

    for (var i = 0; i < totalColumns; i++) {
      // Evita que la columna "id" (primera) se analice
        var columnName = table.column(i).header().textContent.trim().toLowerCase();
        if (columnName === 'id') {
            continue; // saltamos la columna id
        }
        var isEmpty = true;

        table.column(i).nodes().each(function (cell) {
            var content = jQuery(cell).text().trim();
            if (content !== '' && content != '0') {
                isEmpty = false;
                return false; // rompe el loop
            }
        });

        table.column(i).visible(!isEmpty, false); // NO dibujes aún
    }

    table.columns.adjust();
    table.draw(false);
}



function hideEmptyColumns2(selector) {
    var emptyColumnsIndexes = []; // store index of empty columns here
    // check each column separately for empty cells
    jQuery(selector).find('th').each(function(i) {
        // get all cells for current column
        var cells = jQuery(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')');
        var emptyCells = 0;
 
        cells.each(function(cell) {
            // increase emptyCells if current cell is empty, trim string to remove possible spaces in cell
            if ((jQuery(this).html().trim() === '') || (jQuery(this).html() == 0)) {
                emptyCells++;
            }
        });
 
        // if all cells are empty push current column to emptyColumns
        if (emptyCells === jQuery(cells).length) {
            emptyColumnsIndexes.push(jQuery(this).index());
        }
    });
 
    // only make changes if there are columns to hide
    if (emptyColumnsIndexes.length > 0) {
        /* add class never to all empty columns
            never is a special class of the Responsive extension:
            Columns with class never will never be visible, regardless of the browser width, and the data will not be shown in a child row
        */
        jQuery((selector).DataTable().columns(emptyColumnsIndexes).header()).addClass('never');
        // Recalculate the column breakpoints based on the class information of the column header cells, class never will now be available to Responsive extension
        jQuery(selector).DataTable().columns.adjust().responsive.rebuild();
        // immediatly call recalc to have Responsive extension updae the display for the cahnge in classes
        jQuery(selector).DataTable().columns.adjust().responsive.recalc();
    }
}

function download()
{
var titles = [];
var data = [];
jQuery('#nichetabla th').each(function() {
    titles.push(jQuery(this).text());
  });

jQuery('#nichetabla td').each(function() {
    data.push(jQuery(this).text());
  });
  
var CSVString = prepCSVRow(titles, titles.length, '');
CSVString = prepCSVRow(data, titles.length, CSVString);

var downloadLink = document.createElement("a");
  var blob = new Blob(["\ufeff", CSVString]);
  var url = URL.createObjectURL(blob);
  downloadLink.href = url;
  downloadLink.download = "data.csv";

document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
  
}

 /*
* Convert data array to CSV string
* @param arr {Array} - the actual data
* @param columnCount {Number} - the amount to split the data into columns
* @param initial {String} - initial string to append to CSV string
* return {String} - ready CSV string
*/

function prepCSVRow(arr, columnCount, initial) {
  var row = ''; // this will hold data
  var delimeter = ','; // data slice separator, in excel it's `;`, in usual CSv it's `,`
  var newLine = '\r\n'; // newline separator for CSV row

  /*
   * Convert [1,2,3,4] into [[1,2], [3,4]] while count is 2 
   * @param _arr {Array} - the actual array to split
   * @param _count {Number} - the amount to split
   * return {Array} - splitted array
   */
  function splitArray(_arr, _count) {
    var splitted = [];
    var result = [];
    _arr.forEach(function(item, idx) {
      if ((idx + 1) % _count === 0) {
        splitted.push(item);
        result.push(splitted);
        splitted = [];
      } else {
        splitted.push('"'+item+'"');
      }
    });
    return result;
  }
  var plainArr = splitArray(arr, columnCount);
  // don't know how to explain this
  // you just have to like follow the code
  // and you understand, it's pretty simple
  // it converts `['a', 'b', 'c']` to `a,b,c` string
  plainArr.forEach(function(arrItem) {
    arrItem.forEach(function(item, idx) {
      row += item + ((idx + 1) === arrItem.length ? '' : delimeter);
    });
    row += newLine;
  });
  return initial + row;
}




