using Devkoes.Restup.WebServer.Http;
using Devkoes.Restup.WebServer.Rest;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Newtonsoft.Json;
using Windows.Foundation;
using Devkoes.Restup.WebServer.File;
using Microsoft.Practices.Unity;

namespace WebSocketService
{
    public sealed class StartupTask : IBackgroundTask
    {
        private const string APP_DB_DIR_NAME = "DataCenterService";
        private RestRouteHandler _restRouteHandler;

        private HttpServer _httpServer;

        private BackgroundTaskDeferral _deferral;

        private SQLite.Net.SQLiteConnection _conn;
        private string _path;

        /// <remarks>
        /// If you start any asynchronous methods here, prevent the task
        /// from closing prematurely by using BackgroundTaskDeferral as
        /// described in http://aka.ms/backgroundtaskdeferral
        /// </remarks>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // This deferral should have an instance reference, if it doesn't... the GC will
            // come some day, see that this method is not active anymore and the local variable
            // should be removed. Which results in the application being closed.
            _deferral = taskInstance.GetDeferral();
            
            var httpServer = new HttpServer(8800);
            _httpServer = httpServer;

            _restRouteHandler = new RestRouteHandler();
            _restRouteHandler.RegisterController<RestService>();

            //register the route to handle the api
            httpServer.RegisterRoute("api", _restRouteHandler);
            //register the route to handle the base web pages..
            httpServer.RegisterRoute(new StaticFileRouteHandler(@"Website"));

            _path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "db.sqlite");
            try
            {
                _conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), _path);
                _conn.CreateTable<UserIdentity>();
                _conn.CreateTable<TimeLog>();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            await httpServer.StartServerAsync();

            // Dont release deferral, otherwise app will stop
        }
    }
}
