import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import '../models/project.dart'; class StorageService { static const String _projectsFileName = 'unityudp_projects.json'; Future get _localPath async { final directory = await getApplicationDocumentsDirectory(); return directory.path; } Future get _projectsFile async { final path = await _localPath; return File('$path/$_projectsFileName'); } Future saveProjects(List projects) async { try { final file = await _projectsFile; final jsonList = projects.map((p) => p.toJson()).toList(); final jsonString = const JsonEncoder.withIndent(' ').convert(jsonList); await file.writeAsString(jsonString); } catch (e) { rethrow; } } Future> loadProjects() async { try { final file = await _projectsFile; // Check if file exists if (!await file.exists()) { return []; } final contents = await file.readAsString(); if (contents.isEmpty) { return []; } final List jsonList = json.decode(contents); return jsonList.map((json) { // Migration: Add ipAddress field if it doesn't exist (for backwards compatibility) if (!json.containsKey('ipAddress')) { json['ipAddress'] = '127.0.0.1'; // Default IP address } return Project.fromJson(json); }).toList(); } catch (e) { return []; } } Future getProjectsFilePath() async { final file = await _projectsFile; return file.path; } Future importProjectsFromFile(String filePath) async { try { final importFile = File(filePath); if (!await importFile.exists()) { return false; } final contents = await importFile.readAsString(); final List jsonList = json.decode(contents); final projects = jsonList.map((json) { // Migration: Add ipAddress field if it doesn't exist (for backwards compatibility) if (!json.containsKey('ipAddress')) { json['ipAddress'] = '127.0.0.1'; // Default IP address } return Project.fromJson(json); }).toList(); // Save the imported projects await saveProjects(projects); return true; } catch (e) { return false; } } Future exportProjectsToFile(String filePath, List projects) async { try { final exportFile = File(filePath); final jsonList = projects.map((p) => p.toJson()).toList(); final jsonString = const JsonEncoder.withIndent(' ').convert(jsonList); await exportFile.writeAsString(jsonString); return true; } catch (e) { return false; } } }