using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace c3stream.Pages {
	public class ConferenceModel : PageModel {
		public static    List<TalkMetadata>       EventMetadata = new List<TalkMetadata>();
		private readonly ILogger<ConferenceModel> _logger;

		public ConferenceModel(ILogger<ConferenceModel> logger) => _logger = logger;

		public void OnGet() {
			var guid  = Request.Query["guid"];
			var state = Request.Query["state"];
			if (string.IsNullOrWhiteSpace(guid) || string.IsNullOrWhiteSpace(state) || !HttpContext.Session.Keys.Contains("bookmark"))
				return;

			lock (c3stream.Lock) {
				ReadEventMetadata();
				var existing = EventMetadata.FirstOrDefault(p => p.Guid == guid)
											?.State.FirstOrDefault(p => p.Guid == HttpContext.Session.GetString("bookmark"));
				if (existing != null)
					existing.State = state;
				else
					EventMetadata.FirstOrDefault(p => p.Guid == guid)?.State.Add(new UserState(HttpContext.Session.GetString("bookmark"), state));
				WriteEventMetadata();
				Response.Redirect("/");
			}
		}

		public static TalkMetadata GetEvent(string guid) {
			TalkMetadata metadata;
			lock (c3stream.Lock) {
				ReadEventMetadata();
				using (var wc = new WebClient()) {
					var json = wc.DownloadString($"https://api.media.ccc.de/public/events/{guid}");
					var talk = Talk.FromJson(json);
					metadata = new TalkMetadata(guid, talk);
					EventMetadata.Add(metadata);
				}

				WriteEventMetadata();
			}

			return metadata;
		}

		public static void ReadEventMetadata() {
			lock (c3stream.Lock)
				EventMetadata = JsonConvert.DeserializeObject<List<TalkMetadata>>(System.IO.File.ReadAllText(c3stream.DbPath));
		}

		public static void WriteEventMetadata() {
			System.IO.File.WriteAllText(c3stream.DbPath, JsonConvert.SerializeObject(EventMetadata));
		}

		public class TalkMetadata {
			public readonly string          Guid;
			public          List<UserState> State;
			public          Talk            Talk;

			public TalkMetadata(string guid, Talk talk) {
				Guid  = guid;
				State = new List<UserState>();
				Talk  = talk;
			}
		}

		public class UserState {
			public string Guid;
			public string State;

			public UserState(string guid, string state = "unwatched") {
				Guid  = guid;
				State = state;
			}
		}
	}
}