﻿using Microsoft.Owin;
using SS.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Host.SystemWeb;
using System.Security.Claims;
using System.Reflection;

namespace SS.Web.Controllers
{
    public class AccountController : Controller
    {
        [ChildActionOnly]
        public ActionResult Welcome()
        {
            var claim = User.Identity as ClaimsIdentity;

            return PartialView("_Welcome", new AccountWelcomeModel
            {
                IsAuthenticated = Request.IsAuthenticated,
                Username = Request.IsAuthenticated ? claim.FindFirst(ClaimTypes.Name).Value : "anonymous",
                RoleName = Request.IsAuthenticated ? claim.FindFirst(ClaimTypes.Role).Value : "n/a"
            });
        }

        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult Login(AccountLoginModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
                return View();

            // create identity
            ClaimsIdentity identity = new ClaimsIdentity(Startup.AUTHENTICATION_TYPE);
            identity.AddClaim(new Claim(ClaimTypes.Name, model.Name));
            identity.AddClaim(new Claim(ClaimTypes.Role, model.Role));

            // sign in
            HttpContext.GetOwinContext().Authentication.SignIn(identity);

            if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            else
                return RedirectToAction("Index", "Home");
        }

        public ActionResult Logout(string returnUrl)
        {
            HttpContext.GetOwinContext().Authentication.SignOut(Startup.AUTHENTICATION_TYPE);

            if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            else
                return RedirectToAction("Index", "Home");
        }

        [Authorize]
        public ActionResult MyAccount()
        {
            var claim = User.Identity as ClaimsIdentity;
            var knownClaimNames = new Lazy<Dictionary<string, string>>(() =>
            {
                // maps short claim names to schema
                // nothing special, only for display
                return typeof(ClaimTypes)
                    .GetFields(BindingFlags.Public | BindingFlags.Static)
                    .Where(f => f.IsLiteral)
                    .ToDictionary(f => f.GetRawConstantValue().ToString(), f => f.Name);
            }, true);

            return View(claim.Claims
                .ToDictionary(
                c => knownClaimNames.Value.ContainsKey(c.Type) ? knownClaimNames.Value[c.Type] : c.Type,
                c => c.Value));
        }        
    }
}