<script>
import { ref, computed, watch } from 'vue';
// This is used to make the user select a file (from their computer) to parse locally
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { setDataRows } from "@/components/forms/other/MassDataInserter.vue";
import Swal from "sweetalert2";

// File content
const fileContent = ref('');
// File content
const selectFile = ref('');
// Parsed file content
const parsedFileContent = ref(null);
// Define the onParsedFunction
const onParsedFunctionCache = ref(null);

const showError = (message) => {
  Swal.fire({
    icon: 'error',
    title: 'Error',
    text: message,
    confirmButtonText: SessionUser.objects.global.language.close,
  });
}

export const initiateFileSelection = (onParsedFunction = null) => {
  // Reset the file content
  fileContent.value = '';
  // Reset the parsed file content
  parsedFileContent.value = null;
  // Reset the select file
  selectFile.value = '';
  // Set the onParsedFunction
  if (onParsedFunction) {
    onParsedFunctionCache.value = onParsedFunction;
  } else {
    onParsedFunctionCache.value = null;
  }
  // Create a file input element
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.csv, .txt'; // Accept only CSV and TXT files

  // Listen for the change event
  fileInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        fileContent.value = e.target.result;
        // You can now use the file content as needed
        //console.log('File content:', fileContent.value);
        if (validateFileContent(fileContent.value)) {
          // If the file content is valid, parse it
          parseFileContent(fileContent.value);
        }
      };
      reader.readAsText(file);
    }
  });

  // Trigger the file input click
  fileInput.click();
};

export const getFileContent = () => {
  return fileContent.value;
};

const validateFileContent = (content) => {
  // Check if the content is empty
  if (!content) {
    showError('File content is empty');
    return false;
  }

  // Check if the content has at least one row
  const rows = content.split('\n');
  if (rows.length === 0) {
    showError('File has no rows');
    return false;
  }

  // Check if the first row has at least one column
  const columns = rows[0].split(',');
  if (columns.length === 0) {
    showError('File has no columns');
    return false;
  }

  return true;
};

const cleanRow = (row) => {
  // Remove leading and trailing whitespace
  row = row.trim();
  // Remove any extra commas
  row = row.replace(/,+/g, ',');
  // Remove any trailing commas
  row = row.replace(/,$/, '');
  // Remove \r and \n characters
  row = row.replace(/\r/g, '');
  // Replace \t with ;
  row = row.replace(/\t/g, ';');
  return row;
};

const parseFileContent = (content) => {
  // Split the content by new lines
  const rows = content.split('\n');
  // Clean up the rows
  rows.forEach((row, index) => {
    rows[index] = cleanRow(row);
  });
  // Split each row by commas (or other delimiters)
  // This assumes that the file is a CSV file
  const parsedData = rows.map(row => row.split(';'));
  // Remove empty rows, and columns
  parsedData.forEach((row, index) => {
    if (row.length === 0 || row[0] === '') {
      parsedData.splice(index, 1);
    }
    row.forEach((column, index) => {
      if (column === '') {
        row.splice(index, 1);
      }
    });
  });
  // Set the parsed data to the dataRows
  console.log(parsedData);
  parsedFileContent.value = parsedData;
  // Run the onParsed function
  onParsed(onParsedFunctionCache.value);
};

const onParsed = (onParsedFunction) => {
  // Check if the onParsedFunction is set
  if (onParsedFunction) {
    // Call the onParsedFunction with the parsed data
    onParsedFunction(parsedFileContent.value);
  } else {
    // If no onParsedFunction is set, just set the dataRows
    showError('No onParsedFunction set');
  }
};
</script>