// gcode-worker.js

self.onmessage = function (event) {
  const { configString } = event.data
  const configObject = {}
  let isThumbnailSection = false
  let base64ImageData = ''
  const lines = configString.split('\n')
  const totalLines = lines.length

  for (let i = 0; i < totalLines; i++) {
    const line = lines[i]
    let trimmedLine = line.trim()

    // Skip empty lines or lines that are not part of the config
    if (!trimmedLine || !trimmedLine.startsWith(';')) {
      continue
    }

    // Remove the leading semicolon and trim the line
    trimmedLine = trimmedLine.substring(1).trim()

    // Handle thumbnail section
    if (trimmedLine.startsWith('thumbnail begin')) {
      isThumbnailSection = true
      base64ImageData = '' // Reset image data
      continue
    } else if (trimmedLine.startsWith('thumbnail end')) {
      isThumbnailSection = false
      configObject.thumbnail = base64ImageData // Store base64 string as-is
      continue
    }

    if (isThumbnailSection) {
      base64ImageData += trimmedLine // Accumulate base64 data
      continue
    }

    // Split the line into key and value parts
    let [key, ...valueParts] = trimmedLine.split('=').map((part) => part.trim())

    if (!key || !valueParts.length) {
      continue
    }

    if (
      key === 'end_gcode' ||
      key === 'start_gcode' ||
      key === 'start_filament_gcode' ||
      key === 'end_filament_gcode'
    ) {
      continue
    }

    const value = valueParts.join('=').trim()

    // Handle multi-line values (assuming they start and end with curly braces)
    if (value.startsWith('{')) {
      let multiLineValue = value
      while (!multiLineValue.endsWith('}')) {
        // Read the next line
        const nextLine = lines[++i].trim()
        multiLineValue += '\n' + nextLine
      }
      // Remove the starting and ending braces
      configObject[key.replace(/\s+/g, '_').replace('(', '').replace(')', '')] =
        multiLineValue.substring(1, multiLineValue.length - 1).trim()
    } else {
      key = key.replace('[', '').replace(']', '')
      key = key.replace('(', '').replace(')', '')
      // Regular key-value pair
      configObject[key.replace(/\s+/g, '_')] = value
        .replace('"', '')
        .replace('"', '')
    }

    // Report progress
    const progress = ((i + 1) / totalLines) * 100
    self.postMessage({ type: 'progress', progress })
  }

  // Post the result back to the main thread
  self.postMessage({ type: 'result', configObject })
}
