using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;

using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;

namespace WebApplication1.Controllers {
  [Authorize( Users = "agathe.zepower@monsieurmadame.fr" )]
  public class ExempleGestionUtilisateursController : Controller {

    ApplicationUserManager _ApplicationUserManager = null;
    public ApplicationUserManager ApplicationUserManager { // Pour les opérations classiques
      get {
        if( _ApplicationUserManager == null )
          _ApplicationUserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); // Ssi using Microsoft.AspNet.Identity.Owin 
        return _ApplicationUserManager;
      }
    }

    private ApplicationDbContext _DC = null;
    public ApplicationDbContext DC { // Pour un accès libre à la base de données
      get {
        if( _DC == null ) {
          _DC = new ApplicationDbContext();
          //_DC.Configuration.ProxyCreationEnabled = false;
        }
        return _DC;
      }
    }


    public ActionResult Index() {
      //var test = from r in DC.Roles
      //           select new {
      //             Name = r.Name,
      //             Users = from ruID in r.Users
      //                     join u in DC.Users on ruID.UserId equals u.Id
      //                     select u.UserName
      //           };
      ViewBag.Utilisateurs = DC.Users.Include( u => u.Roles ).OrderBy( u => u.UserName ).ToDictionary( u => u.Id ); // u.Roles ne contient des (RoleId + UserId) !
      ViewBag.Roles = DC.Roles.Include( r => r.Users ).OrderBy( r => r.Name ).ToDictionary( r => r.Id );        // Idem pour r.Users !
      return View( DC.Users.Find( User.Identity.GetUserId() ) );
    }
    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult CreerRole( string nvRole ) {
      try {
        DC.Roles.Add( new IdentityRole( nvRole ) );
        DC.SaveChanges();
      }
      catch {
      }
      return RedirectToAction( "Index" );
    }

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult DonnerLeRoleALUtilisateur( string role, string utilisateur ) {
      ApplicationUserManager.AddToRole( utilisateur, role );
      return RedirectToAction( "Index" );
    }

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult EnleverLeRoleALUtilisateur( string role, string utilisateur ) {
      ApplicationUserManager.RemoveFromRole( utilisateur, role );
      return RedirectToAction( "Index" );
    }

    protected override void Dispose( bool disposing ) {
      if( disposing ) {
        if( _DC != null )
          _DC.Dispose();
        if( _ApplicationUserManager != null )
          _ApplicationUserManager.Dispose();
      }
      base.Dispose( disposing );
    }

  }
}