from typing import Dict, Optional
import json
from .interfaces import TaskManagerInterface, TaskModel
from .task import Task
from diona.project.storage import get_storage_instance

class TaskManager(TaskManagerInterface):
    """Task manager implementation."""
    
    def __init__(self):
        self.storage = get_storage_instance()
        self.tasks: Dict[str, TaskModel] = {}
        self._load_tasks()
    
    def _load_tasks(self):
        """Load tasks from storage."""
        try:
            # Get all task files in the scheduler directory
            import os
            scheduler_dir = self.storage.get_path("scheduler", "", storage_type="project")
            
            if os.path.exists(scheduler_dir):
                for file_name in os.listdir(scheduler_dir):
                    if file_name.endswith(".json"):
                        task_name = file_name[:-5]  # Remove .json extension
                        file_path = file_name
                        
                        # Read task data
                        task_data_str = self.storage.read("scheduler", file_path, storage_type="project")
                        if task_data_str:
                            import json
                            task_data = json.loads(task_data_str)
                            
                            # Create task from data
                            task = Task.from_dict(task_data)
                            self.tasks[task_name] = task
                            print(f"Loaded task: {task_name}")
        except Exception as e:
            print(f"Error loading tasks: {e}")
    
    def register_task(self, task: TaskModel) -> bool:
        """Register a new task."""
        try:
            # Store task in memory
            self.tasks[task.get_task_name()] = task
            
            # Store task metadata in file
            task_data = task.to_dict()
            file_path = f"{task.get_task_name()}.json"
            self.storage.write("scheduler", file_path, json.dumps(task_data, ensure_ascii=False, indent=2), storage_type="project")
            
            return True
        except Exception as e:
            print(f"Error registering task: {e}")
            return False
    
    def get_task(self, task_name: str) -> Optional[TaskModel]:
        """Get task by name."""
        return self.tasks.get(task_name)
    
    def list_tasks(self) -> Dict[str, TaskModel]:
        """List all tasks."""
        return self.tasks
    
    def unregister_task(self, task_name: str) -> bool:
        """Unregister a task."""
        try:
            # Remove from memory
            if task_name in self.tasks:
                del self.tasks[task_name]
            
            # Remove from file
            file_path = f"{task_name}.json"
            if self.storage.exists("scheduler", file_path, storage_type="project"):
                self.storage.delete("scheduler", file_path, storage_type="project")
            
            return True
        except Exception as e:
            print(f"Error unregistering task: {e}")
            return False
    
    def update_task(self, task: TaskModel) -> bool:
        """Update a task."""
        return self.register_task(task)
