using Discord;
using System;
using UnityEngine;

namespace Cryville.Crtr {
	internal class DiscordController : MonoBehaviour {
		public static DiscordController Instance;

		const long CLIENT_ID = 1059021675578007622L;

		Discord.Discord dc;
		ActivityManager am;
		long launchTime;

		void Start() {
			Instance = this;
			launchTime = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
			dc = new Discord.Discord(CLIENT_ID, (UInt64)CreateFlags.Default);
			am = dc.GetActivityManager();
			SetIdle();
		}

		void Update() {
			dc.RunCallbacks();
		}

		void OnApplicationQuit() {
			dc.Dispose();
		}

		void Callback(Result result) { }

		public void SetIdle() {
			am.UpdateActivity(new Activity {
				State = "Idle",
				Instance = false,
				Timestamps = { Start = launchTime },
			}, Callback);
		}

		public void SetPlaying(string detail, double? duration) {
			long now = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
			am.UpdateActivity(new Activity {
				State = "Playing a chart",
				Details = detail,
				Instance = true,
				Timestamps = {
					Start = now,
					End = duration == null ? 0 : now + (long)duration,
				},
			}, Callback);
		}
	}
}
