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

using Newtonsoft.Json;
using Pingchuan.BeijingSafeguard.BLL;
using Pingchuan.BeijingSafeguard.Model;

namespace Pingchuan.BeijingSafeguard.App.Controllers
{
    public class MengguController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public void GetMap(int type, int zoom, int x, int y)
        {
            GmapNetCache map = GmapNetCacheBLL.Get(type, zoom, x, y);
            if (map != null)
            {
                Response.StatusCode = 200;
                Response.AddHeader("Content-Type", "image/png");
                Response.BinaryWrite(map.Tile);
                Response.End();
            }
            else
            {
                Response.StatusCode = 404;
                Response.AddHeader("Content-Type", "text/plain");
                Response.BinaryWrite(Encoding.UTF8.GetBytes("Tile not found."));
                Response.End();
            }
        }

        [HttpPost]
        public void AddTask(string taskId, string region, decimal longitude, decimal latitude, decimal height, decimal simulatedDuration, decimal simulatedInterval, DateTime releaseTime, int resultState, string resultMessage)
        {
            User user = GetLoginUser();
            TaskBLL.Add(user.OrgId, user.Id, taskId, region, longitude, latitude, height, simulatedDuration, simulatedInterval, releaseTime, resultState, resultMessage);
        }

        [HttpPost]
        public int AddTag(int userId, string taskId, string name)
        {
            return TagBLL.Add(userId, taskId, name);
        }

        [HttpPost]
        public void DeleteTag(int id)
        {
            TagBLL.Delete(id);
        }

        [HttpPost]
        public void DeleteTagsByName(string userId, string name)
        {
            TagBLL.DeleteByTagName(userId, name, "mg");
        }

        [HttpPost]
        public JsonResult GetTaskTags(int userId, string taskId)
        {
            return Json(TagBLL.GetTags(userId, taskId));
        }

        [HttpPost]
        public string GetUserTags(int userId)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            return JsonConvert.SerializeObject(TagBLL.GetList(userId), Formatting.Indented, setting);
        }

        [HttpPost]
        public JsonResult GetTasks(int userId, DateTime startTime, DateTime endTime, List<string> tags)
        {
            List<Task> tasks = TaskBLL.GetList(userId, "mg", startTime, endTime, tags);
            return Json(tasks);
        }

        [HttpPost]
        public JsonResult GetTags(int userId, string taskId)
        {
            return Json(TagBLL.GetTags(userId, taskId));
        }

        [HttpPost]
        public void DeleteTask(string id)
        {
            TaskBLL.Delete(id);
        }
    }
}