﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web.Http;
using DoubleDollar.Data.DataAccess;

namespace DoubleDollar.WebAPI.Controllers
{
    public class DoubleDollarApiController : ApiController
    {
        public IDataLayer DataLayer { get; set; }

        public DoubleDollarApiController()
        {
            this.DataLayer = new DataLayer();
        }

        public int UserID
        {
            get
            {
                ClaimsIdentity ident = this.User?.Identity as ClaimsIdentity;

                if (ident == null || !ident.HasClaim(a => a.Type == "UserID"))
                {
                    return -1;
                }

                int userID = 0;

                string rawUserID = ident.Claims.FirstOrDefault(a => a.Type == "UserID")?.Value;

                int.TryParse(rawUserID ?? "", out userID);

                return userID;
            }
        }

        [NonAction]
        public new void Dispose()
        {
            base.Dispose();
            if (this.DataLayer is IDisposable)
            {
                ((IDisposable)this.DataLayer).Dispose();
            }
        }
    }
}