import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

class PluginUtils {
  /// Test if path_provider is working correctly
  static Future<bool> testPathProvider() async {
    try {
      // Try different methods of path_provider to see which one works
      if (kIsWeb) {
        debugPrint('Running on web platform, path_provider has limited functionality');
        return true;
      }
      
      // Try to get temporary directory
      try {
        final tempDir = await getTemporaryDirectory();
        debugPrint('Temporary directory: ${tempDir.path}');
      } catch (e) {
        debugPrint('Error getting temporary directory: $e');
      }
      
      // Try to get application documents directory
      try {
        final appDocDir = await getApplicationDocumentsDirectory();
        debugPrint('Application documents directory: ${appDocDir.path}');
      } catch (e) {
        debugPrint('Error getting application documents directory: $e');
      }
      
      // Try to get application support directory
      try {
        final appSupportDir = await getApplicationSupportDirectory();
        debugPrint('Application support directory: ${appSupportDir.path}');
      } catch (e) {
        debugPrint('Error getting application support directory: $e');
      }
      
      return true;
    } catch (e) {
      debugPrint('Path provider test failed: $e');
      return false;
    }
  }
  
  /// Create a fallback directory when path_provider fails
  static Future<Directory> getFallbackDirectory() async {
    if (Platform.isAndroid) {
      return Directory('/data/data/com.example.tugas_akhir_supabase/cache');
    } else if (Platform.isIOS) {
      return Directory(Platform.environment['HOME']! + '/Documents');
    } else if (Platform.isWindows) {
      final tempPath = Platform.environment['TEMP'] ?? 'C:\\Windows\\Temp';
      return Directory('$tempPath\\flutter_temp');
    } else if (Platform.isMacOS) {
      return Directory('/tmp/flutter_temp');
    } else if (Platform.isLinux) {
      return Directory('/tmp/flutter_temp');
    } else {
      throw UnsupportedError('Unsupported platform for fallback directory');
    }
  }
  
  /// Get a temporary directory, with fallback if path_provider fails
  static Future<Directory> getSafeTemporaryDirectory() async {
    try {
      return await getTemporaryDirectory();
    } catch (e) {
      debugPrint('Error getting temporary directory, using fallback: $e');
      final fallbackDir = await getFallbackDirectory();
      if (!fallbackDir.existsSync()) {
        fallbackDir.createSync(recursive: true);
      }
      return fallbackDir;
    }
  }
} 