//
        // GET: Vraag/View/detailNum
        public ActionResult View(int id)
        {
            HTMLSanitizer hs = new HTMLSanitizer();
            Markdown md = new Markdown();

            //questiondetails
            var questionDetails = from questionDetail in db.Questions
                                  where questionDetail.QuestionID == id
                                  select questionDetail;
            questionDetails.First().Views += 1;
            db.SaveChanges();
            // check if logged in
            if (User.Identity.IsAuthenticated)
            {
                // give back the rank of this user
                ViewBag.UserRank = (from user in db.Users
                                    where user.UserName == User.Identity.Name
                                    select user.Rank).Single();
            }
            Question questionDetailView = questionDetails.First();

            // Sanitize the post content and title
            // Then process the content with Markdown
            questionDetailView.Title = hs.EscapeHTMLentities(questionDetailView.Title);
            questionDetailView.Content = hs.Sanitize(questionDetailView.Content, HTMLSanitizerOption.UnescapeMarkDown);
            questionDetailView.Content = md.Transform(questionDetailView.Content);

            ViewBag.QuestionDetail = questionDetailView;

            List<TagsIDs> abc = new List<TagsIDs>();

            // get all the tags on this question
            var TagList = from tagsQuestion in db.Tags
                          join c in db.QuestionTags on tagsQuestion.TagID equals c.TagId
                          where c.QuestionId == id
                          select tagsQuestion;
            // add each to the list
            foreach (Tag i in TagList)
            {
                abc.Add(new TagsIDs(i, id));

                // Sanitize each tag its name
                i.Name = hs.Sanitize(i.Name, HTMLSanitizerOption.StripTags);
            }

            ViewBag.Helper = abc;

            // get the user of this question (for the username and link)
            var useringlist = from users in db.Users
                              where users.UserID == questionDetailView.UserId
                              select users;

            ViewBag.QuestionUser = useringlist.First();

            // get the comments on this question
            var commentList = from comments in db.Comments
                              orderby comments.Created_At descending
                              where comments.QuestionId == id
                              select comments;
            // add each to the list
            List<Comment> commentUserView = new List<Comment>(commentList);
            ViewBag.CommentsList = commentList;

            // get a list of all the users that made the comment
            List<User> CommentingUsers = new List<User>();
            foreach (Comment commentje in commentUserView)
            {
                var userComment = from commentse in db.Users
                                  where commentse.UserID == commentje.UserId
                                  select commentse;
                CommentingUsers.Add(userComment.First());
            }

            ViewBag.UserCommentList = CommentingUsers;

            // get the answers
            var answerQuestion = from answers in db.Answers
                                 orderby answers.Created_At descending
                                 where answers.QuestionId == id
                                 select answers;
            List<Answer> answerQuestionView = new List<Answer>(answerQuestion);
            ViewBag.AnswerQuestionList = answerQuestion;

            // Set the count to 'n' or 'geen' if there are no answers yet
            ViewBag.AnswerCount = answerQuestion.Count();
            ViewBag.AnswerQuestionCount = answerQuestion.Count() > 0 ? answerQuestion.Count().ToString() : "geen" ;

            List<User> AnsweringUsers = new List<User>();
            List<Comment> AnswerComments = new List<Comment>();
            List<User> qCommentUsers = new List<User>();
            // for each answer
            foreach (Answer answertje in answerQuestionView)
            {
                // get the userID (for the username)
                var userAnswer = from answerse in db.Users
                                 where answerse.UserID == answertje.UserId
                                 select answerse;

                AnsweringUsers.Add(userAnswer.First());

                // get al the comments
                var answerCommentList = from qcomments in db.Comments
                                        orderby qcomments.Created_At descending
                                        where qcomments.AnswerId == answertje.AnswerID
                                        select qcomments;

                if (answerCommentList.Count() > 0)
                {
                    // if there are some comments add them
                    foreach (Comment cba in answerCommentList)
                        AnswerComments.Add(cba);
                }
                // foreach comment get the user (for the username again)
                foreach (Comment qCommentje in answerCommentList)
                {
                    var userQComment = from qcommentse in db.Users
                                       where qcommentse.UserID == qCommentje.UserId
                                       select qcommentse;

                    qCommentUsers.Add(userQComment.First());
                }

                // Sanitize the content of the answer and process it with Markdown
                answertje.Content = hs.Sanitize(answertje.Content, HTMLSanitizerOption.UnescapeMarkDown);
                answertje.Content = md.Transform(answertje.Content);
            }
            ViewBag.UserAnswerList = AnsweringUsers;
            ViewBag.AnswerComments = AnswerComments;
            ViewBag.qCommentList = qCommentUsers;

            return View();
        }
        public ActionResult Nieuw(Vraag info)
        {
            HTMLSanitizer hs = new HTMLSanitizer();
            Markdown md = new Markdown();
            // to mark the first time (meaning don't check the tags if there are some new ones)
            bool firstTime = false;
            // check where we came from
            if (Request.UrlReferrer.LocalPath == "/vraag/check")
                firstTime = true; // set the first time if we came from there
            if (info.vraag == null) // check if the question isn't empty
                ModelState.AddModelError("", "Ga terug en voer een titel voor je vraag in.");
            else if (info.vraag != null && (info.tags == null || info.content == null) && !firstTime) // check if all the fields are filled in
                ModelState.AddModelError("", "Vul alle velden in aub.");
            else if (!firstTime)
            {
                // Fields are met hmm let's see if we can find all the tags perhaps :D
                List<string> tagsList = new List<string>(); // new generic list which will contain our tags which we aren't in the database
                info.tags = info.tags.Trim(',', '!', '?', ':', ';', '.');
                string[] tags = info.tags.Split(' '); // assume all tags are splitted by a space (beg)
                if (tags.Count() > 5)
                    ModelState.AddModelError("", " U mag niet meer dan 5 tags meegeven.");
                List<string> foundTags = new List<string>();
                // check if the given tag exits in the datebase
                foreach (string tag in tags)
                {
                    var temp = from taggies in db.Tags
                               where taggies.Name.Contains(tag)
                               select taggies;
                    // if a tag is in the database the above query should find it. Else it is a new one.
                    if (temp.Count() == 0)  // not found add it to the list of new tags
                        tagsList.Add(tag);
                    else // else mark it as one we have already
                        foundTags.Add(tag);
                }

                // get the user information
                var userPosting = from postingUser in db.Users
                                  where postingUser.UserName == User.Identity.Name
                                  join userCombine in db.UserMeta on postingUser.UserID equals userCombine.UserId
                                  select userCombine;
                if (userPosting.Count() != 1)
                {
                    ModelState.AddModelError("", "U bent niet ingelogd."); // aan name dat de join lukt
                    ViewBag.LoggedIn = false;
                }
                // check if we got all new tags filled in and everything is valid
                if ((tagsList.Count() - info.CountTagsSumbitted()) == 0 && ModelState.IsValid)
                {
                    // add the stuff since we are done :D
                    // also check if we have tags to add. If so. Let's add those first (so we can link stuff)
                    int UserID = userPosting.First().UserId;
                    var userPostingMeta = (from usermeta in db.UserMeta
                                           where usermeta.UserId == UserID
                                           select usermeta).Single();

                    // add each new tag to the database
                    for (int i = 0; i < tagsList.Count(); i++)
                    {
                        Tag newTag = new Tag() { Description = info.returnTagContent(i), Name = tagsList.ElementAt(i), Count = 1 };
                        userPostingMeta.Tags += 1;
                        db.Tags.Add(newTag);
                    }
                    // inceremnt the amount of questions that there are with this tag
                    foreach (string tagName in foundTags)
                    {
                        var tagAdd = from tagSelected in db.Tags
                                     where tagSelected.Name.Contains(tagName)
                                     select tagSelected;
                        tagAdd.First().Count += 1;
                    }

                    // add the amount of questions asked by this person with one
                    userPosting.First().Questions += 1;
                    UserMeta userInfo = userPosting.First();
                    // create the question
                    Question newQuestion = new Question() { Title = info.vraag, UserId = userInfo.UserId, Content = info.content };
                    // add it to the db
                    db.Questions.Add(newQuestion);
                    db.SaveChanges(); // to make sure that if there were new tags they are added propperly (so we can query the id's right)

                    // ####################################
                    //     check if we got a new badge
                    // ####################################
                    if (TagBadge.badgeAchieve(userInfo.UserId))
                        TagBadge.awardBadge(userInfo.UserId);
                    if (TagCreatorBadge.badgeAchieve(userInfo.UserId))
                        TagCreatorBadge.awardBadge(userInfo.UserId);
                    if (TagLordBadge.badgeAchieve(userInfo.UserId))
                        TagLordBadge.awardBadge(userInfo.UserId);
                    // ####################################

                    // query back our last question
                    // should be the first of this list
                    var justAsked = from questionAsked in db.Questions
                                    where questionAsked.UserId == userInfo.UserId
                                    orderby questionAsked.Created_At descending
                                    select questionAsked;
                    // query all the id's needed
                    Question justAskedQuestion = justAsked.First();
                    // foreach tag that there in on this question craete a tagID - QuestionID line
                    foreach (string tagje in tags)
                    {
                        // get the id and created an new QuestionTag for it
                        var tagIDPost = from tagIDje in db.Tags
                                        where tagIDje.Name.Contains(tagje)
                                        select tagIDje.TagID;
                        int postTag = tagIDPost.First();

                        QuestionTag newQuestTag = new QuestionTag() { QuestionId = justAskedQuestion.QuestionID, TagId = postTag };
                        db.QuestionTags.Add(newQuestTag);
                    }
                    db.SaveChanges();

                    // #################################
                    //    Check if we got a new badge
                    // #################################
                    if (QuestionBadge.badgeAchieve(userInfo.UserId))
                        QuestionBadge.awardBadge(userInfo.UserId);
                    if (QuestionCreatorBadge.badgeAchieve(userInfo.UserId))
                        QuestionCreatorBadge.awardBadge(userInfo.UserId);
                    if (QuestionLordBadge.badgeAchieve(userInfo.UserId))
                        QuestionLordBadge.awardBadge(userInfo.UserId);
                    // #################################

                    // if we get here we are done :D so take us to our just asked question
                    return RedirectToAction("view", "vraag", new { id = justAskedQuestion.QuestionID });
                }
                else
                {
                    // missing tags :<
                    // create a list for the missing tags :<
                    ViewBag.MissingTagList = tagsList;
                    // give allong a counter (since viewbag is doing nasty and won't let me count :<)
                    ViewBag.MissingTagListCount = tagsList.Count();
                }

            }
            return View();
        }