using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ClipTrimDotNet.Client
{
    public class ClipTrimClient
    {
        private static ClipTrimClient? instance;
        public static ClipTrimClient Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ClipTrimClient();
                }
                return instance;
            }
        }

        private HttpClient httpClient;

        public ClipTrimClient()
        {
            httpClient = new HttpClient()
            {
                BaseAddress = new Uri("http://localhost:5010/"),
                Timeout = TimeSpan.FromSeconds(10)
            };
            Task.Run(ShortPoll);
        }

        public async Task ShortPoll()
        {
           while (true)
            {  
                await GetMetadata();
                await Task.Delay(TimeSpan.FromSeconds(5)); await Task.Delay(TimeSpan.FromSeconds(5));

            }
        }

        public List<CollectionMetaData> Collections { get; private set; } = new List<CollectionMetaData>();
        public CollectionMetaData? SelectedCollection { get; private set; }
        public int PageIndex { get; private set; } = 0;
        private async Task GetMetadata()
        {
            try
            {
                var response = await httpClient.GetAsync("meta");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    dynamic collections = JsonConvert.DeserializeObject(json);
                    collections = collections.collections;
                    Collections = JsonConvert.DeserializeObject<List<CollectionMetaData>>(collections.ToString());
                }
            }
            catch (Exception ex)
            {
                //Logger.Instance.LogMessage(TracingLevel.INFO, $"Error pinging ClipTrim API: {ex.Message}");
                return;
            }

        }

        public List<string> GetCollectionNames()
        {
            //await GetMetadata();
            return Collections.Select(x => x.Name).ToList();
        }

        public void SetSelectedCollectionByName(string name)
        {
            var collection = Collections.FirstOrDefault(x => x.Name == name);
            if (collection != null)
            {
                SelectedCollection = collection;
                PageIndex = 0;
            }
        }

        public ClipMetadata? GetClipByPagedIndex(int index)
        {
            if (SelectedCollection == null) return null;
            int clipIndex = PageIndex * 10 + index;
            if (clipIndex >= 0 && clipIndex < SelectedCollection.Clips.Count)
            {
                return SelectedCollection.Clips[clipIndex];
            }
            return null;
        }

        public async void PlayClip(ClipMetadata? metadata)
        {
           if (metadata == null) return;

            var response = await httpClient.PostAsync("playback/start", new StringContent(JsonConvert.SerializeObject(metadata), Encoding.UTF8, "application/json"));
            if (!response.IsSuccessStatusCode)
            {
                //Logger.Instance.LogMessage(TracingLevel.INFO, $"Error playing clip: {response.ReasonPhrase}");
            }
        }
    }
}
