using Elwig.Helpers;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace Elwig.Windows {
    public abstract class ContextWindow : Window {

        public static readonly int RenewSec = 10;

        protected AppDbContext Context { get; private set; }
        protected bool LockContext { get; set; } = false;

        private readonly DispatcherTimer _timer;
        private bool _renewPending = false;

        public ContextWindow() : base() {
            _timer = new DispatcherTimer();
            _timer.Tick += new EventHandler(OnShouldRenewContext);
            _timer.Interval = new TimeSpan(0, 0, RenewSec);
            _timer.Start();
            Context = new();
            Loaded += OnLoaded;
        }

        public async Task HintContextChange() {
            _renewPending = true;
            if (LockContext) return;
            await RenewContext();
        }

        private async void OnShouldRenewContext(object? sender, EventArgs? evt) {
            if (!Context.HasBackendChanged) return;
            await HintContextChange();
        }

        protected async void OnLoaded(object? sender, RoutedEventArgs? evt) {
            await OnRenewContext();
        }

        protected override void OnClosed(EventArgs evt) {
            base.OnClosed(evt);
            Context.Dispose();
        }

        protected async Task RenewContext() {
            if (!_renewPending) return;
            Context.Dispose();
            Context = new();
            await OnRenewContext();
            _renewPending = false;
        }

        abstract protected Task OnRenewContext();
    }
}