using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RedSocial.Models;

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;

namespace RedSocial.Controllers
{
    public class PostsController : Controller
    {
        private Entities db = new Entities();

        /******************** USER ********************/
        // GET: Posts/Create
        [Authorize(Roles = GlobalConstants.RoleUser)]
        public ActionResult CreatePostPartial()
        {
            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email");
            return View();
        }

        // POST: Posts/Create
        // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
        // más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = GlobalConstants.RoleUser)]
        public void CreatePostPartial([Bind(Include = "Id,Text,DateTime,UserId")] Post post, HttpPostedFileBase file, string video)
        {
            if (ModelState.IsValid)
            {
                var p = db.Posts.Add(post);
                db.SaveChanges();
                if (file != null)
                {
                    Media media = new Media();
                    media.Type = GlobalConstants.TypePhoto;
                    media.Url = Upload.UploadImage(file, GlobalConstants.RoutePostImages, this.Server);
                    media.PostId = p.Id;
                    db.Medias.Add(media);
                    db.SaveChanges();
                }
                if (!String.IsNullOrEmpty(video))
                {
                    Media media = new Media();
                    media.Type = GlobalConstants.TypeVideo;
                    media.Url = video;
                    media.PostId = p.Id;
                    db.Medias.Add(media);
                    db.SaveChanges();
                }
            }

            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", post.UserId);
            Response.Redirect(Request.UrlReferrer.ToString());
        }
       
        // POST: Posts/Delete/5
        [HttpPost, ActionName("DeletePostPartial")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = GlobalConstants.RoleUser)]
        public void DeletePostPartial(int id)
        {
            Post post = db.Posts.Find(id);
            db.Posts.Remove(post);
            db.SaveChanges();
            Response.Redirect(Request.UrlReferrer.ToString());
        }

        // GET: Posts/MyPosts
        [Authorize(Roles = GlobalConstants.RoleUser)]
        public ActionResult MyPosts()
        {
            var id = User.Identity.GetUserId();
            AspNetUser user = db.AspNetUsers.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            var posts = user.Posts;
            var posts_ordered = posts.OrderByDescending(x => x.DateTime);
            return View(posts_ordered.ToList());
        }

        // GET: Posts/MyFriendsPosts
        [Authorize(Roles = GlobalConstants.RoleUser)]
        public ActionResult MyFriendsPosts()
        {
            //recuperar el usuario actual
            var id = User.Identity.GetUserId();
            AspNetUser user = db.AspNetUsers.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            //recuperar los posts de los amigos
            var friends = user.AspNetUsers;
            List<Post> posts = new List<Post>();
            foreach (var friend in friends)
            {
                List<Post> friendPosts = friend.Posts.ToList();
                posts.AddRange(friendPosts);
            }
            //recuperar los posts del usuario
            posts.AddRange(user.Posts.ToList());
            //ordenar por fecha
            var posts_ordered = posts.OrderByDescending(x => x.DateTime);
            return View(posts_ordered.ToList());
        }

        /******************** ADMIN ********************/
        // GET: Posts
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Index()
        {
            var posts = db.Posts.Include(p => p.AspNetUser);
            return View(posts.ToList());
        }

        // GET: Posts/Details/5
        //[Authorize(Roles = GlobalConstants.RoleAdmin)]
        //public ActionResult Details(int? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    Post post = db.Posts.Find(id);
        //    if (post == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(post);
        //}

        // GET: Posts/Create
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Create()
        {
            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email");
            return View();
        }

        // POST: Posts/Create
        // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
        // más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Create([Bind(Include = "Id,Text,DateTime,UserId")] Post post)
        {
            if (ModelState.IsValid)
            {
                var p = db.Posts.Add(post);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", post.UserId);
            return View(post);
        }

        // GET: Posts/Edit/5
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Post post = db.Posts.Find(id);
            if (post == null)
            {
                return HttpNotFound();
            }
            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", post.UserId);
            return View(post);
        }

        // POST: Posts/Edit/5
        // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
        // más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Edit([Bind(Include = "Id,Text,DateTime,UserId")] Post post)
        {
            if (ModelState.IsValid)
            {
                db.Entry(post).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", post.UserId);
            return View(post);
        }

        // GET: Posts/Delete/5
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Post post = db.Posts.Find(id);
            if (post == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        // POST: Posts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = GlobalConstants.RoleAdmin)]
        public ActionResult DeleteConfirmed(int id)
        {
            Post post = db.Posts.Find(id);
            db.Posts.Remove(post);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

    }
}
