using System;
using System.Linq;
using Devkoes.Restup.WebServer.Models.Schemas;
using Devkoes.Restup.WebServer.Attributes;
using System.IO;

namespace WebSocketService
{
    [RestController(InstanceCreationType.Singleton)]
    internal partial class RestService
    {
        private static SQLite.Net.SQLiteConnection _conn;
        private static string _path;

        public RestService()
        {
            if (string.IsNullOrEmpty(_path))
                _path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
            if (_conn == null)
            {
                _conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), _path);
                _conn.CreateTable<UserIdentity>();
                _conn.CreateTable<TimeLog>();
            }
        }

        /// <summary>
        /// Make sure the number of parameters in your UriFormat match the parameters in your method and
        /// the names (case sensitive) and order are respected.
        /// </summary>
        [UriFormat("/simpleparameter/{id}/property/{propName}")]
        public GetResponse GetWithSimpleParameters(int id, string propName)
        {
            return new GetResponse(
                GetResponse.ResponseStatus.OK,
                new DataReceived()
                {
                    ID = id,
                    PropName = propName
                });
        }

        [UriFormat("/postTest")]
        public PostResponse Post([FromContent] DataReceived rcv)
        {
            return new PostResponse(PostResponse.ResponseStatus.Created, $"/simpleparameter/{rcv.ID}/property/{rcv.PropName}");
        }

        //This is the method you need.
        [UriFormat("/postSwipeData")]
        public PostResponse PostWeather([FromContent] CardDataPostDto cardData)
        {
            var userQuery = _conn.Query<UserIdentity>(
                "select * from UserIdentity where CardUId = ?",
                cardData.CardUId);

            var userId = 0;
            if (!userQuery.Any())
            {
                userId = _conn.Insert(new UserIdentity
                {
                    CardUId = cardData.CardUId,
                    FirstName = "?",
                    LastName = "?",
                    HoursPerWeek = 37.0f
                });
            }
            else
            {
                userId = userQuery.First().Id;
            }

            var timeLog = new TimeLog
            {
                SwipeEventDateTime = DateTime.UtcNow,
                UserId_FK = userId
            };

            var tLogId = _conn.Insert(timeLog);
            return new PostResponse(PostResponse.ResponseStatus.Created);
        }
    }
}
