using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Text;
using System.Data.Entity;

using Model.Entities.Users;
using Web.Models.Base;
using Web.Models;

namespace Web.Controllers.API
{

    public class UserController : Base.BaseApiController
    {   

        //[HttpPost]
        //public JsonResult CreateUser(string Login, string Password)
        //{
        //    UOW.Repo_User.Create(new User()
        //    {
        //        Login = Login,
        //        Password = Password,
        //        IsActive = true,
        //        Groups = new List<Group>()
        //        {
        //            UOW.Repo_Group.GetDefaultGroup(EnumDefaultGroups.Пользователи)
        //        }
        //    });

        //    return Json(true, JsonRequestBehavior.AllowGet);
        //}


        [HttpPost]
        public JsonResult GetUserList()
        {
            UserListMode json;

            if (CurrentUser != null && CurrentUser.IsAdmin)
            {
                var users = UOW.Repo_User.All_NoTrack.Include(e => e.Groups).ToList();
                var groups = UOW.Repo_Group.All_NoTrack_List;
                groups.RemoveAll(e => e.Name == EnumDefaultGroups.Анонимные.ToString());

                var model = users.Select(e => new EditUserModel()
                {
                    ID = e.ID,
                    Name = e.Login,
                    Password = "",
                    Changes = EnumChanges.NoChange,
                    Active = e.IsActive,
                    Groups = groups.Select(e2 => new GroupInfo()
                    {
                        ID = e2.ID,
                        Name = e2.Name,
                        EnterInGroup = e.Groups.FirstOrDefault(e3 => e3.ID == e2.ID)!=null
                    }).ToList()
                }).ToList();


                json = new UserListMode(true)
                {
                    Users = model,
                    Groups = groups.Select(e => new GroupInfo()
                    {
                        ID = e.ID,
                        Name = e.Name
                    }).ToList()
                };
                
            }
            else
            {
                json = new UserListMode(false)
                {
                    PermissionError = true,
                    ResMessage = "Need admin"                    
                };
            }

            return Json(json);
        }

        [HttpPost]
        public JsonResult SetUserList(List<EditUserModel> model)
        {
            if (!CurrentUser.IsAdmin)
                return Json(new BaseApiResult(false, "", ""));

            var groups = UOW.Repo_Group.All_List;
            StringBuilder res = new StringBuilder();
            bool HaveErr = false;

            foreach (var elem in model)
            {
                var groups_id = elem.Groups.
                    Where(g => g.EnterInGroup).
                    Select(g => g.ID);

                try
                {
                    switch (elem.Changes)
                    {
                        case EnumChanges.Create:
                            UOW.Repo_User.Create(
                                new User(elem.Name, elem.Password, elem.Active,
                                groups.Where(e => groups_id.Contains(e.ID))));

                            res.Append(elem.ID + "Ok");
                            break;
                        case EnumChanges.Update:
                            var edited = UOW.Repo_User.All.
                                FirstOrDefault(e => e.ID == elem.ID);
                            edited.Login = elem.Name;
                            edited.Password = string.IsNullOrEmpty(elem.Password) ? edited.Password : elem.Password;
                            edited.IsActive = elem.Active;
                            edited.Groups = new List<Group>(
                                groups.Where(e => groups_id.Contains(e.ID)));
                            UOW.Repo_User.Update(edited);

                            res.Append(elem.ID + "Ok");
                            break;
                        case EnumChanges.Delete:
                            UOW.Repo_User.Delete(
                                UOW.Repo_User.All.
                                FirstOrDefault(e => e.ID == elem.ID));

                            res.Append(elem.Name + "|Ok|");
                            break;
                    }
                }
                catch (Exception ex)
                {
                    res.Append(elem.Name + "|Error|" + ex.Message);
                    HaveErr = true;
                }
            }

            return Json(new BaseApiResult(!HaveErr, res.ToString(), "SetUserList"));
        }


        public class UserListMode : BaseApiResult
        {
            public UserListMode(bool Successe) : base(Successe, "", "UserList") { }

            public List<EditUserModel> Users;
            public List<GroupInfo> Groups;
        }



        //[HttpPost]
        //public JsonResult GetGroupList()
        //{
        //    GroupListMode json;

        //    if (CurrentUser != null && CurrentUser.IsAdmin)
        //    {
        //        var groups = UOW.Repo_Group.All_NoTrack_List;

        //        var model = users.Select(e => new EditUserModel()
        //        {
        //            ID = e.ID,
        //            Name = e.Login,
        //            Password = "",
        //            Changes = EnumChanges.NoChange,
        //            Active = e.IsActive,
        //            Groups = groups.Select(e2 => new GroupInfo()
        //            {
        //                ID = e2.ID,
        //                Name = e2.Name,
        //                EnterInGroup = e.Groups.FirstOrDefault(e3 => e3.ID == e2.ID) != null
        //            }).ToList()
        //        }).ToList();


        //        json = new UserListMode(true)
        //        {
        //            Users = model,
        //            Groups = groups.Select(e => new GroupInfo()
        //            {
        //                ID = e.ID,
        //                Name = e.Name
        //            }).ToList()
        //        };

        //    }
        //    else
        //    {
        //        json = new UserListMode(false)
        //        {
        //            PermissionError = true,
        //            ResMessage = "Need admin"
        //        };
        //    }

        //    return Json(json);
        //}
        //[HttpPost]
        //public JsonResult SetGroupList() { }

        public class GroupListMode
        {

        }

    }
}