using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using Pullenti.Util;

namespace Pullenti.Documentory.WebServer.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            StringBuilder html = new StringBuilder();
            var st = MvcApplication.Status;
            if (st == ServerStatus.Starting) html.Append("Сервер стартует... ");
            else if (st == ServerStatus.Stoped) html.Append("Сервер остановлен");
            else if (st == ServerStatus.Stoping) html.Append("Сервер останавливается...");
            else if (MvcApplication.Locals.Count == 0)
                html.Append("Документории не открыты (папка AppData не содержит директорий)");
            else
            {
                html.Append("<table border=\"1pt\"><tr><th>Documentory Id</th><th>Count</th><th>Modified</th><th>Status</th></tr>");
                foreach (var d in MvcApplication.Locals)
                {
                    html.AppendFormat("\r\n<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>", d.Doc.Id, d.Doc.DocumentsCount, 
                        d.LastWrite == DateTime.MinValue ? "-" : MiscHelper.OutDateTime(d.LastWrite));
                    if (!d.Doc.Enabled) html.Append("не доступен");
                    else if (d.OTyp == OperType.ReloadAll) html.AppendFormat("<b>переиндексация, id={0}</b>", d.OParam);
                    else
                    {
                        if (d.OTyp == OperType.LoadingDocs && (DateTime.Now - d.LastWrite).TotalSeconds > 120)
                            d.OTyp = OperType.No;
                        if (d.OTyp == OperType.LoadingDocs) html.Append("<b>загрузка документов</b>");
                        else html.Append("ок");
                    }
                    html.Append("</td></tr>");
                }
                html.Append("\r\n</table>");
            }

            html.Append("\r\n<p style=\"font-family:monospace\">");
            var li = ConsoleHelper.GetLastLines();
            if (li != null)
                for (int i = li.Count - 1; i >= 0; i--)
                    html.AppendFormat("<br/>\r\n{0}", li[i].Replace("  ", " "));
            html.Append("\r\n</p>");

            ViewData["Html"] = html.ToString();
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
