//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34003
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using Facepunch;
using LeatherLoader;
using RustProto;
using System.Reflection;
using System.IO;
using UnityEngine;
using System.Collections;


namespace LimitedSleepers
{
	[Bootstrap]
	public class LimitedSleepersBootstrap : Facepunch.MonoBehaviour
	{
		private DateTime nextUpdate = DateTime.MinValue;
		private int sleeperLifeInMinutes = 15;

		public void Awake()
		{
			DontDestroyOnLoad (this.gameObject);
		}

		public void ReceiveLeatherConfiguration(LeatherConfig config) {
			string cfgPath = Path.Combine (config.ConfigDirectoryPath, "LimitedSleepers.cfg");
			
			if (File.Exists (cfgPath)) {
				IniParser parser = new IniParser (cfgPath);
				
				String lifeStr = parser.GetSetting ("General", "SleeperLifeInMinutes");
				
				int.TryParse (lifeStr, out this.sleeperLifeInMinutes);
				ConsoleSystem.Log ("Config parsed- sleeper life is "+this.sleeperLifeInMinutes+" minutes.");
			} else {
				ConsoleSystem.Log ("Could not locate LimitedSleepers.cfg");
			}
		}

		public void Update()
		{
			if (nextUpdate < DateTime.UtcNow) {
				nextUpdate = DateTime.MaxValue;
				StartCoroutine("ProcessSleepers");
			}
		}

		public IEnumerator ProcessSleepers() {

			//Get the oldest timestamp permitted for a sleeper to survive
			int oldestTimestamp = POSIX.Time.ElapsedStampSince(TimeSpan.FromMinutes(this.sleeperLifeInMinutes));

			foreach (var avatar in UnityEngine.Object.FindObjectsOfType<SleepingAvatar>()) {
				//Cycle through all the sleepers in the world
				ulong owner = avatar.ownerID;
				RustProto.Avatar playerAvatar = NetUser.LoadAvatar(owner);

				//Check if the player has a SLUMBER away event & a timestamp that's older than the oldest permitted, calculated above
				if (playerAvatar != null && playerAvatar.HasAwayEvent && playerAvatar.AwayEvent.Type == AwayEvent.Types.AwayEventType.SLUMBER && playerAvatar.AwayEvent.HasTimestamp && playerAvatar.AwayEvent.Timestamp < oldestTimestamp) {

					//There's an internal SleepingAvatar.Close method that takes a ulong for the playerID- we call that with
					//reflection
					MethodInfo info = typeof(SleepingAvatar).GetMethod("Close", System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.NonPublic);
					SleepingAvatar.TransientData transientData = (SleepingAvatar.TransientData)info.Invoke(null, new object[] { owner});
					
					if (transientData.exists)
					{
						transientData.AdjustIncomingAvatar(ref playerAvatar);
						NetUser.SaveAvatar(owner, ref playerAvatar);
					}
				}

				yield return 0;
			}

			nextUpdate = DateTime.UtcNow.AddMinutes(1);
		}
	}
}

