using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using DataClasses;

namespace DataRepositories
{
    public static class RepositoryExtender
    {
        /// <summary>
        /// Gets current user full user name.
        /// </summary>
        /// <param name="repository">this repository</param>
        /// <param name="login">login name</param>
        /// <returns>Full user name</returns>
        public static string GetFullUserName(this Repository<UserProfile> repository, string login)
        {
            var userProfile = from u in repository.GetAll()
                              where u.Login.Equals(login)
                              select (u.FirstName + " " + u.LastName);

            return userProfile.Single();
        }


        /// <summary>
        /// Gets Time table for selected room.
        /// </summary>
        /// <param name="repository">this repository</param>
        /// <param name="roomId">roomId of Room object</param>
        /// <returns>List of Schooldays</returns>
        public static List<SchoolDayRoom> GetTimeTableForRoom(this Repository<SchoolDayRoom> repository, int? roomId)
        {
            var timeTable = (from x in repository.GetAll()
                             where x.LessonRoom.Id == roomId
                             select x).ToList();

            return timeTable;
        }


        /// <summary>
        /// Insert new or update existing school room from schooldayparameters.
        /// </summary>
        /// <param name="repository">this repository</param>
        /// <param name="paramaters">dynamics parameters</param>
        /// <returns></returns>
        public static List<string> Insert(this Repository<SchoolDayRoom> repository, SchoolDayRoomParameters paramaters)
        {        
            var dayRepository = new Repository<SchoolDayRoom>(paramaters.Context);
            var schoolDay = paramaters.ExistingId > 0 ? dayRepository.GetById(paramaters.ExistingId) : new SchoolDayRoom();

            schoolDay.Day = paramaters.Day;
            schoolDay.LessonRoom = paramaters.Room;

            for (int i = (int)paramaters.HourFrom; i < (int)paramaters.HourTo; i++)
            {
                PropertyInfo property = typeof(SchoolDayRoom).GetProperty(((LessonHoursEnum)i).ToString());
                property.SetValue(schoolDay, paramaters.Lesson);
            }

            if (paramaters.IsValid)
            {
                paramaters.Lesson.SchoolDay = schoolDay;
                
                if (paramaters.ExistingId > 0)
                {
                    dayRepository.Update(schoolDay);
                }
                else
                {
                    dayRepository.Insert(schoolDay);
                }

                paramaters.DeleteEmptyDays();
            }

            return paramaters.ErrorMsg;
        }
    }
}
