using AspNetCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace AspNetCoreMVC.Controllers
{
    [Route("api/user")] // 컨트롤러 전체 라우터 설정
    public class UserController : Controller
    {
        private static List<User> _users;

        public UserController() : base()
        {
            if (_users != null)
                return;

            _users = new List<User>();
            _users.Add(new User
            {
                Id = 1,
                Name = "James",
                Phone = "123-4567-8910",
                Address = "Somewhere over the rainbow1"
            });
            _users.Add(new User
            {
                Id = 2,
                Name = "Carl",
                Phone = "223-4567-8910",
                Address = "Somewhere over the rainbow2"
            });
            _users.Add(new User
            {
                Id = 3,
                Name = "Tyler",
                Phone = "323-4567-8910",
                Address = "Somewhere over the rainbow3"
            });
            _users.Add(new User
            {
                Id = 4,
                Name = "Jackson",
                Phone = "423-4567-8910",
                Address = "Somewhere over the rainbow4"
            });
            _users.Add(new User
            {
                Id = 5,
                Name = "Philip",
                Phone = "523-4567-8910",
                Address = "Somewhere over the rainbow5"
            });
        }

        [HttpGet("{id}")]
        public JsonResult GetUser(int id)
        {
            var user = _users.SingleOrDefault(u => u.Id == id);
            return Json(user);
        }

        [HttpGet("v2/{id}")]
        public IActionResult GetUser2(int id)
        {
            var user = _users.SingleOrDefault(u => u.Id == id);
            if (user == null)
                return BadRequest("No data found");

            return Ok(user);
        }

        [HttpPost]
        public JsonResult Save([FromBody] User user)
        {
            try
            {
                if (!ModelState.IsValid)
                    return Json(false);

                _users.Add(user);
                return Json(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return Json(false);
            }
        }
    }
}
