using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FastReport.Web;
using FastReportWebCore.MVC.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace FastReportWebCore.MVC.Controllers
{
    [Route("")]
    public class HomeController : Controller
    {
        readonly IWebHostEnvironment _hostingEnvironment;

        public HomeController(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpGet("{reportIndex:int?}")]
        public IActionResult Index(int? reportIndex = 0)
        {
            string dir = FindReportsFolder(Environment.CurrentDirectory);
            var fileList = Directory.GetFiles(dir, "*.frx");

            var model = new HomeModel()
            {
                WebReport = new WebReport(),
                ReportsList = fileList.Select(Path.GetFileNameWithoutExtension).ToArray(),
                //ReportsList = new[]
                //{
                //    "Simple List",
                //    "Labels",
                //    "Master-Detail",
                //    "Badges",
                //    "Interactive Report, 2-in-1",
                //    "Hyperlinks, Bookmarks",
                //    "Outline",
                //    "Complex (Hyperlinks, Outline, TOC)",
                //    "Drill-Down Groups",
                //    "Mail Merge",
                //    "Polygon"
                //},
            };

            string reportFullPath;
            if (reportIndex >= 0 && reportIndex < fileList.Length)
            {
                reportFullPath = fileList[reportIndex.Value];
            }
            else
                reportFullPath = fileList[0];

            var webReport = model.WebReport;
            webReport.Report.Load(reportFullPath);

            var dataSet = new DataSet();
            dataSet.ReadXml(Path.Combine(dir, "nwind.xml"));
            webReport.Report.RegisterData(dataSet, "NorthWind");


            webReport.Designer.Path = "/WebReportDesigner/index.html";
            webReport.Designer.SaveCallBack = "/SaveDesignedReport";
            // Uncomment to use Online Designer
            //webReport.Width = "1000";
            //webReport.Height = "1000";
            //webReport.Mode = WebReportMode.Designer;

            return View(model);
        }

        [HttpGet("prepared/{file}")]
        public IActionResult Prepared(string file)
        {
            var model = new HomeModel()
            {
                WebReport = new WebReport(),
                ReportsList = new[]
                {
                    "Simple List",
                    "Labels",
                    "Master-Detail",
                    "Badges",
                    "Interactive Report, 2-in-1",
                    "Hyperlinks, Bookmarks",
                    "Outline",
                    "Complex (Hyperlinks, Outline, TOC)",
                    "Drill-Down Groups",
                    "Mail Merge"
                },
            };


            string dir = FindReportsFolder(Environment.CurrentDirectory);

            model.WebReport.LoadPrepared(file);

            return View("Index", model);
        }

        private string FindReportsFolder(string startDir)
        {
            for (int i = 0; i < 6; i++)
            {
                startDir = Path.Combine(startDir, "..");
                string directory = Path.Combine(startDir, "Demos", "Reports");
                if (Directory.Exists(directory))
                    return directory;
            }
            throw new Exception("Demos/Reports directory is not found");

        }



        // Call-back for save the designed report 
        [HttpPost("/SaveDesignedReport")]
        public ActionResult SaveDesignedReport(string reportID, [FromQuery(Name = "reportUUID")] string reportName)
        {
            string webRootPath = _hostingEnvironment.WebRootPath;

            Stream reportForSave = Request.Body;
            string pathToSave = Path.Combine(webRootPath, "DesignedReports", reportName);
            if (!Directory.Exists(pathToSave))
                Directory.CreateDirectory(Path.GetDirectoryName(pathToSave));
            using (FileStream file = new FileStream(pathToSave, FileMode.Create))
            {
                reportForSave.CopyToAsync(file);
            }
            return new OkResult();
        }
    }
}

