﻿using System;
using System.Data.Linq;
using System.Linq;

namespace StreetPacMan.Server
{
    public interface IPlayersStorage
    {
        Player GetEntityById(int entityId);
        Player UpdateEntity(int entityId, bool isEnabled, double geoLat, double geoLng);
    }

    public class PlayersStorage : IPlayersStorage
    {
        private readonly IConnectionProvider _ConnectionProvider;
        private readonly IGameRules _GameRules;

        public PlayersStorage(IConnectionProvider connectionProvider, IGameRules gameRules)
        {
            _ConnectionProvider = connectionProvider;
            _GameRules = gameRules;
        }

        public Player GetEntityById(int entityId)
        {
            using (var dbConnection = _ConnectionProvider.GetConnection())
            using (var pacManDataContext = new PacManDataContext(dbConnection))
            {
                var dataLoadOptions = new DataLoadOptions();
                dataLoadOptions.LoadWith<Player>(x => x.Game);
                pacManDataContext.LoadOptions = dataLoadOptions; 
                
                return pacManDataContext
                    .Players
                    .Where(x => x.Id == entityId)
                    .FirstOrDefault();
            }
        }

        public Player UpdateEntity(int entityId, bool isEnabled, double geoLat, double geoLng)
        {
            using (var dbConnection = _ConnectionProvider.GetConnection())
            using (var pacManDataContext = new PacManDataContext(dbConnection))
            {
                var dataLoadOptions = new DataLoadOptions();
                dataLoadOptions.LoadWith<Player>(x => x.Game);
                pacManDataContext.LoadOptions = dataLoadOptions;
                
                var updateEntity = pacManDataContext
                    .Players
                    .Where(x => x.Id == entityId)
                    .First();
                updateEntity.State = (int)(isEnabled?PlayerState.JoinedActivePlaying:PlayerState.JoinedDisabled);
                updateEntity.LastGeoLat = geoLat;
                updateEntity.LastGeoLon = geoLng;
                updateEntity.LastCommunicationAt = DateTime.Now;

                pacManDataContext.SubmitChanges();

                return updateEntity;
            }
        }
    }
}