using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBlogo.NET.BLL;
using MVCBlogo.NET.BO;
using BusinessLogic;
using Utils;
using Spencer;
using System.Web.Configuration;



namespace myblog.Controllers
{
    public class AdminController :ApplicationController
    {
        //
        // GET: /Admin/

        public ActionResult Index(string sort,int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<BlogEntry> model = new List<BlogEntry>();

            if (sort != null)
            {
                model = BlogEntryManager.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);
                return View(model);
            }
            else
            {
                model = BlogEntryManager.GetList().AsQueryable().ToPagedList(page, 5, "id");
                return View(model);
            }
               

            

        }

        [AcceptVerbs("GET")]
        public ActionResult AdminBlogCreate()
        {
            var username = AuthorManage.GetList().Select(a => a.username);
            ViewData["username"] = new SelectList(username);//表示的就是所有用户的一个下拉列表

            ViewData["tag"] = TagManager.GetList();
            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminBlogCreate(FormCollection collection)
        {
            BlogEntry model = new BlogEntry();
            string[] tagCheckBox = collection["TagCheckBox"].Split(',');
            int i =0;
            model.tags.Clear();
            foreach(Tag tag in TagManager.GetList())
            {
                if (tagCheckBox[i] == "true")
                {
                    Tag t = new Tag();
                    t.id = tag.id;
                    t.tagname = tag.tagname;
                    model.tags.Add(t);
                }
                else
                {
                    i = i + 2;
                }
            }

            if (collection["Type"] == "blogentry")
            {
                model.type = Types.blogentry;
            }
            else
            {
                model.type = Types.article;
            }

            int authorId =Convert.ToInt32((AuthorManage.GetList()).Where(a => a.username == collection["username"]).Select(b => b.id).SingleOrDefault());
            model.author = AuthorManage.GetItem(authorId);
            model.allowcomments = collection["CommentCheckBox"].Contains("true");
            model.markprivate = collection["PrivateCheckBox"].Contains("true");
            model.body = collection["body"];
            model.datecreated = System.DateTime.Now;
            model.datepublished = System.DateTime.Now;

            UpdateModel(model, collection.ToValueProvider());
            BlogEntryManager.Save(model);
            return RedirectToAction("index", new { page = 1 });
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AdminBlogEdit(int id)
        {
            BlogEntry model = new BlogEntry();
            model = BlogEntryManager.GetItem((long)id);

            var username = AuthorManage.GetList().Select(a => a.username);

            ViewData["username"] = new SelectList(username);

            ViewData["tag"] = TagManager.GetList();
            return View(model);

        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminBlogEdit(int id, FormCollection collection)
        {
            BlogEntry model = BlogEntryManager.GetItem(id);

            string[] tagCheckBox = collection["TagCheckBox"].Split(',');

            int i = 0;

            model.tags.Clear();

            foreach (Tag tag in TagManager.GetList())
            {
                if (tagCheckBox[i] == "true")
                {
                    Tag t = new Tag();
                    t.id = tag.id;
                    t.tagname = tag.tagname;
                    model.tags.Add(t);

                    i = i + 2;
                }
                else
                {
                    i++;
                }
            }

            if (collection["Type"] == "blogentry")
                model.type = Types.blogentry;
            else
                model.type = Types.article;


            model.author.username = collection["username"];
            model.allowcomments = collection["CommentCheckBox"].Contains("true");
            model.markprivate = collection["PrivateCheckBox"].Contains("true");
            model.body = collection["body"];

            model.datemodified = System.DateTime.Now;

            UpdateModel(model, collection.ToValueProvider());

            BlogEntryManager.Save(model);

            return RedirectToAction("index", new { page = 1 }); 
        }


        public ActionResult AdminBlogDelete(int id)
        {
            BlogEntry model = new BlogEntry();
            model = BlogEntryManager.GetItem((long)id);
            BlogEntryManager.Delete(model);
            return RedirectToAction("index", new { page = 1 });
        }

        /// <summary>
        /// 管理评论的首页的Action方法
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult AdminComments(string sort, int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<Comment> model = new List<Comment>();
            if (sort != null)
            {
                model = CommentManager.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);
                return View(model);
            }
            else
            {
                model = CommentManager.GetList().AsQueryable().ToPagedList(page, 5, "id");
                return View(model);
            }
            

        }

        /// <summary>
        /// 编辑评论内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AcceptVerbs("GET")]
        public ActionResult AdminCommentEdit(int id)
        {
            Comment model = new Comment();
            model = CommentManager.GetItem(id);
            return View(model);
        }
        /// <summary>
        /// 处理评论表单发来的数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [AcceptVerbs("POST")]
        public ActionResult AdminCommentEdit(int id,FormCollection collection)
        {
            Comment model = new Comment();
            model = CommentManager.GetItem(id);

            UpdateModel(model, new string[] { "author", "body" }, collection.ToValueProvider());
            CommentManager.Save(model);
            return RedirectToAction("AdminComments", new { page = 1 });
        }

        /// <summary>
        /// 删除评论的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminCommentDelete(int id)
        {
            Comment model = new Comment();
            model = CommentManager.GetItem(id);
            CommentManager.Delete(model);
            return RedirectToAction("AdminComments", new { page = 1 });
        }

        /// <summary>
        /// 分类管理首页的Action
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult AdminTags(string sort, int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<Tag> model = new List<Tag>();
            if (sort != null)
            {
                model = TagManager.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);

                return View(model);
            }
            else
            {
                model = TagManager.GetList().AsQueryable().ToPagedList(page, 5, "id");

                return View(model);
            }
        }

        [AcceptVerbs("GET")]
        public ActionResult AdminTagEdit(int id)
        {
            Tag model = new Tag();
            model = TagManager.GetItem(id);
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminTagEdit(int id, FormCollection collection)
        {
            Tag model = new Tag();
            model = TagManager.GetItem(id);
            UpdateModel(model, new string[] { "tagname" }, collection.ToValueProvider());
            TagManager.Save(model);
            return RedirectToAction("AdminTags", new { page = 1 });

        }

        /// <summary>
        /// 删除分类时的Action处理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminTagDelete(int id)
        {
            Tag model = new Tag();
            model = TagManager.GetItem(id);
            TagManager.Delete(model);
            return RedirectToAction("AdminTags", new { page = 1 });
        }

        /// <summary>
        /// 添加分类的Action
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs("GET")]
        public ActionResult AdminTagCreate()
        {
            return View();
        }

        [AcceptVerbs("POST")]
        public ActionResult AdminTagCreate(FormCollection collection)
        {
            Tag model = new Tag();
            UpdateModel(model, new string[] { "tagname" }, collection.ToValueProvider());
            TagManager.Save(model);
            return RedirectToAction("AdminTags", new { page = 1 });
        }

        public ActionResult AdminAuthors(string sort, int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<Author> model = new List<Author>();
            if (sort != null)
            {
                model = AuthorManage.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);
                return View(model);
            }
            else
            {
                model = AuthorManage.GetList().AsQueryable().ToPagedList(page, 5, "id");
                return View(model);
            }
        }

        /// <summary>
        /// 请求用户编辑的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AcceptVerbs("GET")]
        public ActionResult AdminAuthorEdit(int id)
        {
            Author model = new Author();
            model = AuthorManage.GetItem(id);
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminAuthorEdit(int id, FormCollection collection)
        {
            Author model = new Author();
            model = AuthorManage.GetItem(id);
            UpdateModel(model, new string[] { "username", "password" }, collection.ToValueProvider());
            AuthorManage.Save(model);
            return RedirectToAction("AdminAuthors", new { page = 1 });

        }
        /// <summary>
        /// 新建用户的Action
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AdminAuthorCreate()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminAuthorCreate(FormCollection collection)
        {
            Author model = new Author();
            UpdateModel(model, new string[] { "username", "password" }, collection.ToValueProvider());
            AuthorManage.Save(model);
            return RedirectToAction("AdminAuthors", new { page = 1 });
        }

        /// <summary>
        /// 处理删除用户信息的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminAuthorDelete(int id)
        {
            Author model = new Author();
            model = AuthorManage.GetItem(id);
            AuthorManage.Delete(model);
            return RedirectToAction("AdminAuthors", new { page = 1 });
        }

        /// <summary>
        /// 文件管理的首页
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult AdminFiles(string sort, int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<File> model = new List<File>();
            if (sort != null)
            {
                model = FileManager.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);
                return View(model);
            }
            else
            {
                model = FileManager.GetList().AsQueryable().ToPagedList(page, 5, "id");
                return View(model);
            }
        }

        /// <summary>
        /// 添加文件的Action
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AdminFileCreate()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminFileCreate(HttpPostedFileBase fileToUpload)
        {
            if (fileToUpload != null)
            {
                MVCBlogo.NET.BO.File file = new MVCBlogo.NET.BO.File();
                file.filename = System.IO.Path.GetFileName(fileToUpload.FileName);
                file.mime = fileToUpload.ContentType;//MIME类型
                byte[] binaryData = new byte[fileToUpload.ContentLength];
                fileToUpload.InputStream.Read(binaryData, 0, fileToUpload.ContentLength);
                file.filecontent = binaryData;
                FileManager.Save(file);
            }
            return RedirectToAction("AdminFiles", new { page = 1 });
        }

        /// <summary>
        /// 删除某文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminFileDelete(int id)
        {
            MVCBlogo.NET.BO.File file = new MVCBlogo.NET.BO.File();
            file = FileManager.GetItem((long)id);
            FileManager.Delete(file);
            return RedirectToAction("AdminFiles", new { page = 1 });
        }

        public ActionResult AdminFileShow(int id)
        {
            ViewData["id"] = id;
            MVCBlogo.NET.BO.File file = new MVCBlogo.NET.BO.File();
            file = FileManager.GetItem((long)id);
            ViewData["name"] = file.filename;
            return View();
        }

        public ActionResult Image(int id)
        {
            MVCBlogo.NET.BO.File myfile = FileManager.GetItem((long)id);
            if (myfile != null)
            {
                FileContentResult fileContentResult = new FileContentResult(myfile.filecontent, myfile.mime);
                return fileContentResult;
            }
            else
            {
                throw new Exception("无法生成该图片:" + id.ToString());
            }
        }

        public ActionResult ImageList()
        {
            JavaScriptResult javaScriptResult = new JavaScriptResult();
            string script = "var tinyMCEImageList = new Array( ";
            int countfiles = FileManager.Count();
            if (countfiles > 0)
            {
                List<MVCBlogo.NET.BO.File> myFiles = FileManager.GetList();
                foreach (MVCBlogo.NET.BO.File myFile in myFiles)
                {
                    script += "[\"" + myFile.filename + "\",\"Image?id=" + myFile.id.ToString() + "\"],";
                }
            }
            script += "[\"---\",\"\"]);";
            javaScriptResult.Script = script;
            return javaScriptResult;

        }

       /// <summary>
       /// 管理日志首页的Action
       /// </summary>
       /// <param name="sort"></param>
       /// <param name="page"></param>
       /// <returns></returns>
        public ActionResult AdminLog(string sort, int? page)
        {
            page = page ?? 0;
            if (page >= 1) page = page - 1;
            List<Log> model = new List<Log>();
            if (sort != null)
            {
                model = LogManager.GetList().AsQueryable().ToPagedList(page, 5, "id", sort);
                return View(model);
            }
            else
            {
                model = LogManager.GetList().AsQueryable().ToPagedList(page, 5, "id");
                return View(model);
            }
        }

        /// <summary>
        /// 显示网站日志的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminLogShow(int id)
        {
            Log model = new Log();
            model = LogManager.GetItem((long)id);
            return View(model);
        }

        /// <summary>
        /// 删除日志的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AdminLogDelete(int id)
        {
            Log log = new Log();
            log = LogManager.GetItem((long)id);
            LogManager.Delete(log);
            return RedirectToAction("AdminLog", new { page = 1 });
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AdminSetupEdit()
        {
            ViewData["BlogTitle"] = BlogSettings.BlogTitle;
            ViewData["BlogDescription"] = BlogSettings.BlogDescription;
            ViewData["RootPath"] = BlogSettings.RootPath;
            ViewData["RSSPageSize"] = BlogSettings.RSSPageSize;
            ViewData["MaxFileSize"] = BlogSettings.MaxFileSize;
            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AdminSetupEdit(FormCollection collection)
        {
            BlogSettings.BlogTitle = collection["blogtilte"];
            BlogSettings.BlogDescription =collection["blogdescription"];
            BlogSettings.RootPath = collection["rootpath"];
            BlogSettings.RSSPageSize =Convert.ToInt32(collection["rsspagesize"]);
            BlogSettings.MaxFileSize =long.Parse(collection["maxfilesize"]);
            BlogSettings.Save();
            return RedirectToAction("AdminSetupEdit");
        }
    }
}
