using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Spice.Data;
using Spice.Models;
using Spice.Utility;

namespace Spice.Areas.Customer.Controllers
{
    [Authorize(Roles = SD.DeviceUser)]
    [Area("Customer")]
    public class DeviceController : Controller
    {
        private readonly ApplicationDbContext _db;

        public DeviceController(ApplicationDbContext db)
        {
            _db = db;
        }
        public async Task<IActionResult> Index()
        {
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            return View(await _db.devices.Where(u=>u.User == claim.Subject.Name).ToListAsync());
        }

        //GET - CREATE
        public IActionResult Create()
        {
            return View();
        }

        //POST - CREATE
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(devices device)
        {
            if (ModelState.IsValid)
            {
                var claimsIdentity = (ClaimsIdentity)this.User.Identity;
                var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
                device.User = claim.Subject.Name;
                _db.devices.Add(device);
                await _db.SaveChangesAsync();

                return RedirectToAction(nameof(Index));
            }
            return View(device);
        }

        //GET-DELETE
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var device1 = await _db.devices.FindAsync(id);
            if(device1 == null)
            {
                return NotFound();
            }
            return View(device1);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var device = await _db.devices.FindAsync(id);
            if(device == null)
            {
                return View();
            }
            _db.devices.Remove(device);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}