using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;
using rockfishCore.Util;

namespace rockfishCore.Controllers
{
    [Produces("application/json")]
    [Route("api/User")]
    [Authorize]
    public class UserController : Controller
    {
        private readonly rockfishContext _context;

        public UserController(rockfishContext context)
        {
            _context = context;
        }

        // GET: api/User
        [HttpGet]
        public IEnumerable<User> GetUser()
        {
            return _context.User;
        }

        // GET: api/User/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetUser([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = await _context.User.SingleOrDefaultAsync(m => m.Id == id);

            if (user == null)
            {
                return NotFound();
            }

            return Ok(user);
        }

        // PUT: api/User/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutUser([FromRoute] long id, [FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != user.Id)
            {
                return BadRequest();
            }

            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/User
        [HttpPost]
        public async Task<IActionResult> PostUser([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.User.Add(user);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetUser", new { id = user.Id }, user);
        }

        // DELETE: api/User/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUser([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = await _context.User.SingleOrDefaultAsync(m => m.Id == id);
            if (user == null)
            {
                return NotFound();
            }

            _context.User.Remove(user);
            await _context.SaveChangesAsync();

            return Ok(user);
        }

        private bool UserExists(long id)
        {
            return _context.User.Any(e => e.Id == id);
        }


        //------------
        
        [HttpPost("{id}/changepassword")]
        public JsonResult ChangePassword([FromRoute] long id, [FromBody] dtoChangePassword cp)
        {
            if (string.IsNullOrWhiteSpace(cp.oldpassword) || string.IsNullOrWhiteSpace(cp.newpassword))
            {
                return Json(new { msg = "UserController:ChangePassword->A required value is missing", error = 1 });
            }

            try
            {
                var user = _context.User.SingleOrDefault(m => m.Id == id);
                string oldhash = Hasher.hash(user.Salt, cp.oldpassword);
                if (oldhash == user.Password)
                {
                    string newhash = Hasher.hash(user.Salt, cp.newpassword);
                    user.Password = newhash;
                    _context.User.Update(user);
                    _context.SaveChanges();
                    return Json(new { msg = "success", ok = 1 });
                }
                else
                {
                    return Json(new { msg = "UserController:ChangePassword->current password does not match", error = 1 });
                }
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message, error = 1 });
            }
        }

        public class dtoChangePassword
        {
            public string oldpassword;
            public string newpassword;

        }



    }
}