/**
 * @fileoverview Utility module for playgroundStorage.js
 * 
 * @module pages.Playground.services.playgroundStorage
 */

import * as Blockly from "blockly/core";

const STORAGE_KEY = "playground-workspace";

export const saveWorkspace = (workspace) => {
  if (!workspace) {
    console.warn("Workspace não fornecido para salvar");
    return false;
  }

  try {
    const json = Blockly.serialization.workspaces.save(workspace);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(json));
    return true;
  } catch (error) {
    console.error("Erro ao salvar workspace:", error);
    return false;
  }
};

export const loadWorkspace = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    return saved ? JSON.parse(saved) : null;
  } catch (error) {
    console.error("Erro ao carregar workspace:", error);
    return null;
  }
};

export const createDebouncedSave = (delay = 1000) => {
  let timeoutId = null;

  return (workspace) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      saveWorkspace(workspace);
    }, delay);
  };
};
