using Bridge.Html5;
using Logging;
using System;
using FetchTypeDefine;
using static Bridge.Html5.Window;
namespace PseudoHotReload
{
public class PhrPollFile
{
private readonly string _stampFile;
private readonly int _interval;
private string _lastStamp;
private int _timeOutId;
public PhrPollFile(string stampFile = "phr-stamp.txt", int interval = 1000, bool start = true)
{
_stampFile = stampFile;
_interval = interval;
if (start) Start();
}
private void CheckStamp()
{
var url = _stampFile + "?" + DateTime.Now.Ticks;
Logger.Debug($"PHR:Fetching:{url}");
new Fetch(url, new FetchParams { Method = "GET" })
.Then(r =>
{
if (false == r.Ok) throw new Exception("Response was not ok.");
return r.Text();
})
.Then(r =>
{
Logger.Debug($"PHR:Fetched:{r ?? "(null)"}");
if (_lastStamp == null)
{
_lastStamp = r;
_timeOutId = SetTimeout(CheckStamp, _interval);
Logger.Debug($"PHR:Stamp stored,started another timer:{_timeOutId}");
}
else if (_lastStamp != r)
{
Logger.Info("PHR:Stamp change detected, reloading...");
Window.Location.Reload(true);
}
else
{
_timeOutId = SetTimeout(CheckStamp, _interval);
Logger.Debug($"PHR:Stamp nochg,started another timer:{_timeOutId}");
}
}).Catch(e =>
{
_timeOutId = SetTimeout(CheckStamp, _interval);
Logger.Debug($"PHR:Server seem down,waiting until alive again,started another timer:{_timeOutId}");
});
}
public void Start()
{
Stop();
_lastStamp = null;
_timeOutId = SetTimeout(CheckStamp, _interval);
Logger.Debug($"PHR:Started on timer:{_timeOutId}");
}
public void Stop()
{
ClearTimeout(_timeOutId);
}
}
}