﻿using Cedita.One.Base.Data;
using Cedita.One.Base.Data.EntityFramework;
using Cedita.One.Base.Web;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Teach.AssetManagement.Models;

namespace Teach.AssetManagement.Controllers
{
    public class AssetsController : DbServiceInjectedController
    {
        // GET: Assets
        public ActionResult Index()
        {
            var assets = DbContext.Assets.ToList();
            return View(assets);
        }
        
        public async Task<ActionResult> Detail(int? id)
        {
            var asset = await DbContext.Assets.FindAsync(id);
            return View(asset);
        }

        [ChildActionOnly]
        public ActionResult AssetDetailTab(int? id)
        {
            var asset = DbContext.Assets.Find(id);
            ViewBag.AssetGroupId = SelectListHelper.CreateFromData(DbContext.AssetGroups, nameof(AssetGroup.AssetGroupId), nameof(AssetGroup.Name), "No Group", asset?.AssetGroup);
            ViewBag.ParentAssetId = SelectListHelper.CreateFromData(DbContext.Assets, nameof(Asset.AssetId), nameof(Asset.Name), "None", asset?.ParentAsset);
            ViewBag.LocationId = SelectListHelper.CreateFromData(DbContext.Locations, nameof(Location.LocationId), nameof(Location.Name), "None", asset?.Location);
            return PartialView("Partials/AssetDetail", asset);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult SaveAsset(Asset model)
        {
            // Remove any errors regarding DateCreated, AssetId
            if (ModelState.ContainsKey(nameof(Asset.DateCreated)))
                ModelState.Remove(nameof(Asset.DateCreated));
            if (ModelState.ContainsKey(nameof(Asset.AssetId)))
                ModelState.Remove(nameof(Asset.AssetId));

            if (ModelState.IsValid)
            {
                if (model.AssetId == 0)
                {
                    model.DateCreated = DateTime.Now;
                    DbContext.Assets.Add(model);
                    TempData["Success"] = "Asset Created.";
                }
                else
                {
                    var dbEntity = DbContext.Assets.Find(model.AssetId);
                    var dbEntry = DbContext.Entry(dbEntity);
                    dbEntry.CurrentValues.SetValues(model);

                    var changeTracker = new ChangeTracker<Asset>(dbEntry) { TreatNullAsBlankString = true };
                    var changes = changeTracker.GetChanges();
                    DbContext.Audits.AddRange(changes.Select(tc => new Audit
                    {
                        Table = "Assets",
                        TableId = model.AssetId,
                        DateCreated = DateTime.Now,
                        UserId = User.Identity.GetUserId(),
                        Field = tc.PropertyName,
                        From = tc.ValueFrom,
                        To = tc.ValueTo
                    }));

                    TempData["Success"] = "Asset Saved.";
                }
                DbContext.SaveChanges();
            }
            
            return RedirectToAction("Index");
        }
    }
}