using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace PostService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {
        private readonly ILogger<HomeController> _logger;

        public static List<Post> list = new List<Post>()
        {
            new Post()
            {
                Id = Guid.NewGuid(),
                Name = "Default"
            }
        };
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        [HttpGet("get")]
        public IActionResult Get()
        {
            return list == null || list.Count == 0 ? NotFound() : Ok(list);
        }

        [HttpGet("get/{Id}")]
        public IActionResult Get([FromRoute] Guid Id)
        {
            var obj = list.Where(l => l.Id == Id).FirstOrDefault();
            return obj == null ? NotFound() : Ok(obj);
        }

        [HttpPost("create")]
        public IActionResult Create([FromBody] CreateUpdatePost data)
        {
            try
            {
                var model = new Post()
                {
                    Id = Guid.NewGuid(),
                    Name = data.Name,
                };

                list.Add(model);

                var modelForResult = new CreateUpdatePost
                {
                    Name = model.Name
                };

                return Ok(modelForResult);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPut("update/{Id}")]
        public IActionResult Update([FromRoute] Guid Id,
                                    [FromBody] CreateUpdatePost data)
        {
            var oldModel = list.Where(l => l.Id == Id).Select(l => list.IndexOf(l)).FirstOrDefault();
            if (oldModel != null)
            {
                list[oldModel].Name = data.Name;

                var modelForResult = new CreateUpdatePost {
                    Name = data.Name,
                };

                return Ok(modelForResult);
            }
            else return NotFound();
        }

        [HttpDelete("delete/{Id}")]
        public IActionResult Delete([FromRoute] Guid Id)
        {
            var model = list.Where(l => l.Id != Id).FirstOrDefault();

            if (model != null) {
                list.Remove(model);
                return Ok();
            }
            else return NotFound();
        }
    }
}
