using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using c3stream.Pages;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;

namespace c3stream {
	public static class c3stream {
		public const  string           DataPath  = "data";
		public const  string           DbFile    = "_c3stream.json";
		public const  string           CachePath = "/mnt/storage/archive/Video/congress/";
		public const  string           CacheUrl  = "https://mirror.c3stream.de/";
		public static object           Lock      = new object();
		public static string           DbPath    = Path.Combine(DataPath, DbFile);
		public static List<UserStatus> UserData  = new List<UserStatus>();

		public static void Main(string[] args) {
			if (!Directory.Exists(DataPath))
				Directory.CreateDirectory(DataPath);
			if (!File.Exists(DbPath))
				ConferenceModel.WriteEventMetadata();
			ConferenceModel.ReadEventMetadata();

			foreach (var e in ConferenceModel.EventMetadata.FindAll(p => p.State != null)) {
				foreach (var state in e.State) {
					lock (Lock) {
						UserData.Add(new UserStatus(state.Guid, e.Guid, state.State));
					}
				}
			}
			WriteUserData();

			//CreateHostBuilder(args).Build().Run();
		}

		public static void UpdateCookie(HttpRequest resquest, HttpResponse response, string redirectUri) {
			//if new bookmark is in uri
			if (resquest.Query.ContainsKey("bookmark") && resquest.Cookies["bookmark"] != resquest.Query["bookmark"]) {
				response.Cookies.Append("bookmark", resquest.Query["bookmark"], new CookieOptions {Expires = DateTimeOffset.MaxValue});
				response.Redirect(redirectUri + "bookmark=" + resquest.Query["bookmark"]);
			}
			//if no cookie exists or cookie is invalid
			else if (!resquest.Cookies.ContainsKey("bookmark") || !Guid.TryParseExact(resquest.Cookies["bookmark"], "D", out _)) {
				var guid = Guid.NewGuid().ToString();
				response.Cookies.Append("bookmark", guid, new CookieOptions {Expires = DateTimeOffset.MaxValue});
				response.Redirect(redirectUri + "bookmark=" + guid);
			}
			//redir to cookie
			else if (!resquest.Query.ContainsKey("bookmark")) {
				response.Redirect(redirectUri + "bookmark=" + resquest.Cookies["bookmark"]);
			}
		}

		public static void WriteUserData() {
			lock (Lock) {
				File.WriteAllText(Path.Combine(DataPath, "c3stream.user.json"), JsonConvert.SerializeObject(UserData));
			}
		}

		public class UserStatus {
			public readonly string TalkId;
			public readonly string UserId;
			public          string State;

			public UserStatus(string userId, string talkId, string state = "unwatched") {
				UserId = userId;
				State  = state;
				TalkId = talkId;
			}
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
	}
}