using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Flowchart.Models;
using MindFusion.Diagramming.Mvc;
using Microsoft.AspNetCore.Hosting;

namespace Flowchart.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment env;

        public HomeController(IWebHostEnvironment env)
        {
            this.env = env;
        }

        public ActionResult Index(string submitButton)
        {
            DiagramView view = DiagramView.FromRequest("diagramView1", Request);
            ViewBag.DiagramView = view;
            switch (submitButton)
            {
                case "Save to XML":
                    return (Save(view));
                default:
                    return (Load(view));
            }
        }

        public ActionResult Load(DiagramView view)
        {
            var path = env.WebRootFileProvider.GetFileInfo("js//Flowchart.xml")?.PhysicalPath;
            view.Diagram.LoadFromXml(path);
            ViewBag.DiagramView = view;
            return View("Index");
        }

        public ActionResult Save(DiagramView view)
        {
            var path = env.WebRootFileProvider.GetFileInfo("js//Flowchart.xml")?.PhysicalPath;
            view.Diagram.SaveToXml(path);
            return View("Index");
        }
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
