using System;
using System.IO;
using System.Reflection;
using Interfaces;
using Nancy;
using Nancy.Extensions;
using Nancy.ModelBinding;

namespace RaceLapTimer.ApiControllers
{
    public class RaceSessionApiModule : NancyModule
    {
        private readonly IDbProvider _provider;
        private readonly INotifierManager _notifier;

        public RaceSessionApiModule(IDbProvider provider
                                    , INotifierManager notifierManager) : base("/api/racesession")
        {
            _provider = provider;
            _notifier = notifierManager;

            Get[""] = args => GetRaceSessions();
            Post["/create"] = args => CreateRaceSession();
            Get["/historic"] = args => GetHistoricRaceSessions();
            Delete["/historic/{id}"] = args => DeleteHistoricRaceSession(args);
            Get["/export/{id}"] = args => GetRaceExport(args);
        }

        private dynamic GetRaceExport(dynamic args)
        {
            throw new NotImplementedException();
        }

        private dynamic DeleteHistoricRaceSession(dynamic args)
        {
            int raceSessionId = args.Id;
            var res = _provider.DeleteRaceSession(raceSessionId);
            return Context.GetRedirect("/history");
        }

        private dynamic GetHistoricRaceSessions()
        {
            var sessions = _provider.GetRaceSessions(false);
            return Response.AsJson(new { data = sessions });
        }

        private dynamic GetRaceSessions()
        {
            var sessions = _provider.GetRaceSessions(true);
            return Response.AsJson(new { data = sessions });
        }

        private dynamic CreateRaceSession()
        {
            var session = this.Bind<RaceSession>();
            var res = _provider.CreateRaceSession(session);
            if (res)
            {
                _notifier.NotifyRaceStarted(new NotificationEventArgs {RaceStartTime = DateTime.UtcNow, MaxLaps = session.MaxLaps});
            }
            return Context.GetRedirect("/racedirector");
        }
    }
}