using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Newtonsoft.Json.Linq;

using Learn_CSS.DI;

using Learn_CSS.Model.Entities;

using Learn_CSS.Model.DAL;

using Learn_CSS.Model.BLL;

namespace Learn_CSS.APP.Web.Controllers
{
    public class ApiTaskController : Controller
    {
        private readonly CSSTaskStorage Storage;
        private readonly TaskService TaskService;        
        


        public ApiTaskController() 
        {
            Storage = DiRegistry.Resolve<CSSTaskStorage>();
            TaskService = DiRegistry.Resolve<TaskService>();
        }


        /// <summary>
        /// Запросить кол-во заданий в хранилище
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Count()
        {
            return Json(Storage.data.Count, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// Прочитать список из файловой системы
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult ReadTasks()
        {
            try
            {
                Storage.Load();
            }
            catch (Exception ex)
            {
                string full_message = "";

                for (var e = ex; e != null; e = e.InnerException)
                    full_message += e.Message;

                return Json(new { Successe = false, Message = full_message, Stack = ex.StackTrace }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { Successe = true }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Получить задание по id
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetTask(int ID)
        {
            var task = Storage.data[ID];

            return Json(task, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// Проверить задание
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Validate(ValidateEntity entity)
        {
            var task = Storage.data[entity.ID];

            var result = TaskService.Validate(task, entity);

            return Json(result);
        }

    }
}