using C1.Web.Mvc;
using C1.Web.Mvc.Serialization;
using DashboardModel;
using System;
using System.Collections;
using System.Globalization;
#if ASPNETCORE
using Microsoft.AspNetCore.Mvc;
using System.IO;
#else
using System.Web.Mvc;
#endif

namespace DashboardDemo.Controllers
{
    public partial class HomeController : Controller
    {
        private static DataService _dataService;
        private string _dataXmlFolderPath;
        public DataService DataService
        {
            get
            {
                return _dataService ?? (_dataService = DataService.GetService(DataXmlFolderPath));
            }
        }
        public string DataXmlFolderPath
        {
            get
            {
                return _dataXmlFolderPath ?? (_dataXmlFolderPath = Path.Combine(Startup.Environment.WebRootPath, "Content"));
            }
        }

        private void UpdateDateRange()
        {
            var range = new DateRange();
    #if ASPNETCORE
            range.Start = (DateTime.ParseExact(this.HttpContext.Request.Query["startDate"], "M/d/yyyy", CultureInfo.InvariantCulture));
            range.End = (DateTime.ParseExact(this.HttpContext.Request.Query["endDate"], "M/d/yyyy", CultureInfo.InvariantCulture));
    #else
            range.Start = (DateTime.ParseExact(this.HttpContext.Request["startDate"], "M/d/yyyy", CultureInfo.InvariantCulture));
            range.End = (DateTime.ParseExact(this.HttpContext.Request["endDate"], "M/d/yyyy", CultureInfo.InvariantCulture));
    #endif
            DataService.DateRange = range;
        }

        public ActionResult Index()
        {
            ViewBag.BudgetItemList = DataService.BudgetItemList;
            ViewBag.DateSaleList = DataService.DateSaleList;
            return View();
        }

        public ActionResult GetTopData()
        {
            UpdateDateRange();
            var respone = new ArrayList();
            var topProducts = DataService.GetTopSaleProductList(3);
            respone.Add(CollectionViewHelper.Read<SaleItem>(new CollectionViewRequest<SaleItem>(), topProducts));
            var topCustomers = DataService.GetTopSaleCustomerList(7);
            respone.Add(CollectionViewHelper.Read<SaleItem>(new CollectionViewRequest<SaleItem>(), topCustomers));
            var goalItems = DataService.CategorySalesVsGoal;
            respone.Add(CollectionViewHelper.Read<SaleGoalItem>(new CollectionViewRequest<SaleGoalItem>(), goalItems));
            var regionalGoalItems = DataService.RegionSalesVsGoal;
            respone.Add(CollectionViewHelper.Read<SaleGoalItem>(new CollectionViewRequest<SaleGoalItem>(), regionalGoalItems));
            return this.C1Json(respone);
        }
    }
}
