using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Nodes;

namespace WebApplication2.Controllers
{
    public class BeritaController : Controller
    {
        public IActionResult Index()
        {
            return View("~/Views/Berita/Berita.cshtml");
        }

        public IActionResult GetBerita()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/json", "berita.json");

            if (!System.IO.File.Exists(path))
                return NotFound();

            var json = System.IO.File.ReadAllText(path);
            return Content(json, "application/json");
        }

        public IActionResult Detail(int id)
        {
            ViewBag.Id = id;
            return View("~/Views/Berita/DetailBerita.cshtml");
        }

        public IActionResult GetDetail(int id)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/json", "berita.json");

            if (!System.IO.File.Exists(path))
                return NotFound();

            var json = System.IO.File.ReadAllText(path);

            var data = JsonNode.Parse(json).AsArray();

            var result = data.FirstOrDefault(x => (int)x["id"] == id);

            if (result == null)
                return NotFound();

            return Json(result);
        }

        public IActionResult GetAll()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/json", "berita.json");
            var json = System.IO.File.ReadAllText(path);
            return Content(json, "application/json");
        }
    }
}