using System;
using System.Collections.Generic;

namespace Quasar.Server.Statistics
{
    public sealed class ClientStatisticsSnapshot
    {
        public ClientStatisticsSnapshot(
            int totalClients,
            int onlineClients,
            int offlineClients,
            IReadOnlyList<CategoryCount> clientsByCountry,
            IReadOnlyList<CategoryCount> clientsByOperatingSystem,
            IReadOnlyList<CategoryCount> topTags,
            DateTime generatedAtUtc,
            string errorMessage = null)
        {
            TotalClients = totalClients;
            OnlineClients = onlineClients;
            OfflineClients = offlineClients;
            ClientsByCountry = clientsByCountry ?? new CategoryCount[0];
            ClientsByOperatingSystem = clientsByOperatingSystem ?? new CategoryCount[0];
            TopTags = topTags ?? new CategoryCount[0];
            GeneratedAtUtc = generatedAtUtc;
            ErrorMessage = string.IsNullOrWhiteSpace(errorMessage) ? null : errorMessage;
        }

        public int TotalClients { get; }

        public int OnlineClients { get; }

        public int OfflineClients { get; }

        public IReadOnlyList<CategoryCount> ClientsByCountry { get; }

        public IReadOnlyList<CategoryCount> ClientsByOperatingSystem { get; }

        public IReadOnlyList<CategoryCount> TopTags { get; }

        public DateTime GeneratedAtUtc { get; }

        public string ErrorMessage { get; }

        public bool HasError => !string.IsNullOrWhiteSpace(ErrorMessage);

        public static ClientStatisticsSnapshot CreateError(string message)
        {
            return new ClientStatisticsSnapshot(
                0,
                0,
                0,
                new CategoryCount[0],
                new CategoryCount[0],
                new CategoryCount[0],
                DateTime.UtcNow,
                message);
        }
    }

    public sealed class CategoryCount
    {
        public CategoryCount(string label, int count, double share)
        {
            Label = string.IsNullOrWhiteSpace(label) ? "Unknown" : label;
            Count = count;
            Share = share;
        }

        public string Label { get; }

        public int Count { get; }

        public double Share { get; }

        public override string ToString()
        {
            return $"{Label} ({Count})";
        }
    }
}
