using Microsoft.AspNet.Identity.EntityFramework;
using Sevomin.Models;
using Sevomin.Models.Helpers;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Linq;

namespace Sevomin.WebFrontend.Controllers
{
    [Authorize]
    public class AuthorizedController : BaseController
    {
        public AuthorizedController()
            : this(new SevominUserManager(new UserStore<User>(SevominDbContext.Current)))
        {
        }

        public AuthorizedController(SevominUserManager userManager)
        {
            UserManager = userManager;
        }

        public SevominUserManager UserManager { get; private set; }

        public async Task<ActionResult> GetResume(string userid = "", bool english = false)
        {
            if (string.IsNullOrWhiteSpace(userid))
                userid = (await UserManager.FindByNameAsync(User.Identity.Name)).Id;
            Dovomin user = await UserManager.FindByIdAsync(userid) as Dovomin;
            if (user == null)
                return HttpNotFound();

            if (!User.IsInRole("God"))
            {
                if (User.IsInRole("Dovomin"))
                {
                    if (userid != user.Id)
                    {
                        return HttpNotFound();
                    }
                    else { }
                }
                else if (User.IsInRole("Avalin"))
                {
                    Avalin avalin = (await UserManager.FindByNameAsync(User.Identity.Name)) as Avalin;
                    bool showIt = avalin.Jobs.Any(j =>
                    {
                        bool ret = j.Applications.Any(c => c.DovominId == userid);
                        return ret;
                    });
                    if (!showIt)
                        return HttpNotFound();
                }
            }
            
            string path = Path.Combine(Server.MapPath("~/App_Data/resumes/"), english ? user.EnglishResume : user.PersianResume);
            string fileDownloadName = string.Format("{0} {1} Resume{2}", user.DisplayName, english ? "English" : "Persian", Path.GetExtension(path));
            return File(path, "application/octet-stream", fileDownloadName);
        }
			
    }
}
