using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Saradomin.Model;

namespace Saradomin.Infrastructure.Services
{
    public class RemoteConfigService : IRemoteConfigService
    {
        private const string ServerProfilesURL =
            "https://assets.emoscape.org/server_profiles.json";

        public ObservableCollection<ServerProfile> AvailableProfiles { get; private set; } = new();

public async Task FetchServerProfileConfig(string outputPath)
{
    using (var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) })
    {
        // Fetch the remote config JSON.
        var configJson = await httpClient.GetStringAsync(ServerProfilesURL);
        Console.WriteLine($"Fetched config from {ServerProfilesURL}:");
        Console.WriteLine(configJson);

        // Get the full path for clarity.
        var fullPath = Path.GetFullPath(outputPath);

        if (File.Exists(outputPath))
        {
            Console.WriteLine($"Deleting existing file at {fullPath}");
            File.Delete(outputPath);
        }
        
        Console.WriteLine($"Writing config to {fullPath}");
        await File.WriteAllTextAsync(outputPath, configJson);
    }
}


        public async Task LoadServerProfileConfig(string filePath)
        {
            using (var sr = new StreamReader(filePath))
            {
                AvailableProfiles = JsonSerializer.Deserialize<ObservableCollection<ServerProfile>>(
                    await sr.ReadToEndAsync()
                );
            }
        }

        public void LoadFailsafeDefaults()
        {
            AvailableProfiles = new ObservableCollection<ServerProfile>
            {
                new()
                {
                    Name = "Local server",
                    ManagementServerAddress = "localhost",
                    GameServerAddress = "localhost",
                    GameServerPort = 43594,
                    WorldListServerPort = 43595,
                    CacheServerPort = 43595
                },

                new()
                {
                    Name = "EmoScape Live Game",
                    ManagementServerAddress = "play.emoscape.org",
                    GameServerAddress = "play.emoscape.org",
                    GameServerPort = 43594,
                    WorldListServerPort = 43595,
                    CacheServerPort = 43595
                },
                
                new()
                {
                    Name = "Original 2009Scape Live Server",
                    ManagementServerAddress = "play.2009scape.org",
                    GameServerAddress = "play.2009scape.org",
                    GameServerPort = 43594,
                    WorldListServerPort = 43595,
                    CacheServerPort = 43595
                },
            };
        }
    }
}
