using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ZpcBulletinBoard.Data;
using ZpcBulletinBoard.Models.Editor;
using System.Linq;
using Microsoft.AspNetCore.Hosting;

namespace ZpcBulletinBoard.Pages.Pages
{
    [Authorize]
    public class EditMainModel(ILogger<EditMainModel> logger, ApplicationDbContext context, IWebHostEnvironment webHostEnvironment) : PageModel
    {
        private readonly ILogger<EditMainModel> _logger = logger;

        public BulletinBoardPage Page { get; set; }
        public IActionResult OnGet(int? idPage)
        {
            if (idPage == null)
                return NotFound();

            var tmpPage = context.BulletinBoardPage.FirstOrDefault(x => x.IdBulletinBoardPage == idPage);
            if (tmpPage == null)
                return NotFound();

            Page = tmpPage;

            return Page();
        }

        //Get
        public IActionResult OnGetBoards()
        {
            var boards= context.BulletinBoards.ToList();

            return new JsonResult(new { successful = true, error = $"", boards });
        }

        public IActionResult OnGetBoard(int id)
        {
            var board = context.BulletinBoards
                .FirstOrDefault(x => x.IdBulletinBoard == id);
            //Ce je ntre board pole json vrze vn
            //foreach (var bulletinBoardPage in board.Pages)
            //{
            //    bulletinBoardPage.BulletinBoard = null;
            //}
            return board == null 
                ? new JsonResult(new { successful = false, error = $"Board with ID {id} not exists!"}) 
                : new JsonResult(new { successful = true, error = $"", board });
        }

        public IActionResult OnGetPage(int id)
        {
            var page = context.BulletinBoardPage
                .Include(x => x.Links)
                .Include(x => x.Notes)
                .FirstOrDefault(x => x.IdBulletinBoardPage == id);

            if (page == null)
                return new JsonResult(new { successful = false, error = $"Page with ID {id} not exists!" });

            foreach (var link in page.Links)
            {
                link.BulletinBoardPage = null;
            }

            foreach (var note in page.Notes)
            {
                note.BulletinBoardPage = null;
            }

            return new JsonResult(new { successful = true, error = "", page });
        }

        //Post
        public IActionResult OnPostBoardPage(BulletinBoardPage page)
        {
            if (page.IdBulletinBoardPage <= 0)
            {
                context.BulletinBoardPage.Add(page);
            }
            else
            {
                var tmpPage = context.BulletinBoardPage.FirstOrDefault(x => x.IdBulletinBoardPage == page.IdBulletinBoardPage);
                if (tmpPage == null)
                    return new JsonResult(new { successful = false, error = $"Page with ID {page.IdBulletinBoardPage} not exists!", page });

                tmpPage.Name = page.Name;
                //tmpPage.Duration = page.Duration;
            }
            context.SaveChanges();

            return new JsonResult(new { successful = true, error = $"", page });
        }

        public IActionResult OnPostNotes(int idBulletinBoardPage, List<Note> notes)
        {
            //Pobrisem katerih ni vec
            var notesToDelete = context.Notes.Where(x => x.IdBulletinBoardPage == idBulletinBoardPage 
                                                          && !notes.Select(y => y.IdNote).Contains(x.IdNote)).ToList();
            notesToDelete.ForEach(x => context.Notes.Remove(x));

            foreach (var note in notes)
            {
                if (note.IdNote <= 0)
                {
                    note.IdNote = default;
                    context.Notes.Add(note);
                }
                else
                {
                    var tmpNote = context.Notes.FirstOrDefault(x => x.IdNote == note.IdNote);
                    if (tmpNote == null)
                        continue;
                    //    return new JsonResult(new { successful = false, error = $"Page with ID {page.IdBulletinBoardPage} not exists!", page });

                    tmpNote.X = note.X;
                    tmpNote.Y = note.Y;
                    tmpNote.Width = note.Width;
                    tmpNote.Height = note.Height;
                    tmpNote.Content = note.Content;
                    tmpNote.Zindex = note.Zindex;
                    tmpNote.ColorClass = note.ColorClass;
                }
            }

            context.SaveChanges();

            return new JsonResult(new { successful = true, error = "" });
        }

        public IActionResult OnPostBoardPageImage(IFormFile? file, int idPage)
        {
            if (file == null)
                return new JsonResult(new { successful = true, error = "No file!" });

            var tmpPage = context.BulletinBoardPage.FirstOrDefault(x => x.IdBulletinBoardPage == idPage);
            if (tmpPage == null)
                return new JsonResult(new { successful = false, error = $"Page with ID {idPage} not exists!" });

            var uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "bulletin-board-images/pages");
            var imageName = "StaticImage_" + idPage + ".svg";
            var filePath = Path.Combine(uploadsFolder, imageName);

            if (System.IO.File.Exists(filePath))
                System.IO.File.Delete(filePath);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            tmpPage.Image = imageName;
            context.SaveChanges();

            return new JsonResult(new { successful = true, error = $"" });
        }
    }
}
