import { Plugin } from 'obsidian';
import { ProjectWorkspace, ItemStatus } from '../../../database/workspace-types';
import { v4 as uuidv4 } from 'uuid';
export const GLOBAL_WORKSPACE_ID = 'global-workspace';
/**
* WorkspaceService using direct Obsidian data storage
*/
export class WorkspaceService {
private plugin: Plugin;
private readonly STORAGE_KEY = 'workspaces';
constructor(plugin: Plugin) {
this.plugin = plugin;
}
/**
* Get all workspaces
*/
async getAllWorkspaces(): Promise<ProjectWorkspace[]> {
const data = await this.plugin.loadData();
return data?.[this.STORAGE_KEY] || [];
}
/**
* Get workspace by ID
*/
async getWorkspace(id: string): Promise<ProjectWorkspace | undefined> {
const workspaces = await this.getAllWorkspaces();
return workspaces.find(w => w.id === id);
}
/**
* Create a new workspace
*/
async createWorkspace(workspaceData: Omit<ProjectWorkspace, 'id'> | string, description?: string): Promise<ProjectWorkspace> {
let newWorkspace: ProjectWorkspace;
if (typeof workspaceData === 'string') {
// Legacy interface - create from name and description
newWorkspace = {
id: uuidv4(),
name: workspaceData,
description: description || '',
rootFolder: '/',
created: Date.now(),
lastAccessed: Date.now(),
activityHistory: [],
checkpoints: [],
completionStatus: {},
associatedNotes: []
};
} else {
// New interface - create from workspace object
newWorkspace = {
id: uuidv4(),
...workspaceData
};
}
const workspaces = await this.getAllWorkspaces();
workspaces.push(newWorkspace);
await this.saveWorkspaces(workspaces);
return newWorkspace;
}
/**
* Update workspace
*/
async updateWorkspace(id: string, updates: Partial<ProjectWorkspace>): Promise<void> {
const workspaces = await this.getAllWorkspaces();
const index = workspaces.findIndex(w => w.id === id);
if (index === -1) {
throw new Error(`Workspace ${id} not found`);
}
workspaces[index] = { ...workspaces[index], ...updates, lastAccessed: Date.now() };
await this.saveWorkspaces(workspaces);
}
/**
* Delete workspace
*/
async deleteWorkspace(id: string): Promise<void> {
const workspaces = await this.getAllWorkspaces();
const filtered = workspaces.filter(w => w.id !== id);
await this.saveWorkspaces(filtered);
}
/**
* Get all workspaces (alias for getAllWorkspaces for backward compatibility)
*/
async getWorkspaces(): Promise<ProjectWorkspace[]> {
return this.getAllWorkspaces();
}
/**
* Add activity to workspace
*/
async addActivity(workspaceId: string, activity: any): Promise<void> {
const workspace = await this.getWorkspace(workspaceId);
if (workspace) {
if (!workspace.activityHistory) {
workspace.activityHistory = [];
}
workspace.activityHistory.push(activity);
await this.updateWorkspace(workspaceId, workspace);
}
}
/**
* Save workspaces to storage
*/
private async saveWorkspaces(workspaces: ProjectWorkspace[]): Promise<void> {
const data = await this.plugin.loadData() || {};
data[this.STORAGE_KEY] = workspaces;
await this.plugin.saveData(data);
}
}