using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Wierszowki.Core;
using Wierszowki.Core.Interfaces;
using Wierszowki.Core.Linq;
using Wierszowki.Services.Interfaces;
using xVal.ServerSide;

namespace Wierszowki.Services
{
    public class UserService : IUserService
    {
        private readonly IRepository<User> _repository;
        public UserService()
        {
            _repository = new LinqRepository<User>();
        }

        public UserService(IRepository<User> repository)
        {
            _repository = repository;
        }


        public bool LoginUser(string login, string password)
        {
            return _repository.Exists(u => u.Login == login && u.Password == password);
        }

        public void Create(User user)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(user);
            if (errors.Any())
                throw new RulesException(errors);

            //TODO: check if the user with given login name exists...

            _repository.Insert(user);
        }

        public void Update(User user)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(user);
            if (errors.Any())
                throw new RulesException(errors);

            var userToUpdate = _repository.Find(user.Id).Single();
            userToUpdate.FirstName = user.FirstName;
            userToUpdate.LastName = user.LastName;
            userToUpdate.Login = user.Login;
            userToUpdate.Password = user.Password;
            
            _repository.Update(userToUpdate);
        }

        public void Delete(User user)
        {
           _repository.Delete(user);
        }

        public User Find(int id)
        {
            return _repository.Find(id).SingleOrDefault();
        }

        public User FindOne(int id)
        {
            return _repository.FindOne(id);
        }

        public User FindOne(Expression<Func<User, bool>> expression)
        {
            return _repository.FindOne(expression);
        }

        public IList<User> FindAll()
        {
            return _repository.FindAll().ToList();
        }
    }
}