summaryrefslogtreecommitdiff
path: root/Project-Unite/Controllers/ContestsController.cs
blob: 143f885b0f903aa5d31d15c78e24ddac71f0ec91 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_Unite.Models;

namespace Project_Unite.Controllers
{
    [Authorize]
    public class ContestsController : Controller
    {
        [AllowAnonymous]
        // GET: Contests
        public ActionResult Index()
        {
            var model = new ApplicationDbContext().Contests.ToArray();
            return View(model);
        }

        public ActionResult ViewContest(string id)
        {
            var db = new ApplicationDbContext();
            var c = db.Contests.FirstOrDefault(x => x.Id == id);
            if (c == null)
                return new HttpStatusCodeResult(404);
            return View(c);
        }

        [RequiresAdmin]
        public ActionResult CloseContest(string id)
        {
            var db = new ApplicationDbContext();
            var c = db.Contests.FirstOrDefault(x => x.Id == id);
            if (c == null)
                return new HttpStatusCodeResult(404);
            c.EndsAt = DateTime.Now;
            db.SaveChanges();
            return RedirectToAction("Index");

        }

        [RequiresAdmin]
        public ActionResult CreateContest()
        {
            var model = new CreateContestViewModel();
            return View(model);
        }

        [RequiresAdmin]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateContest(CreateContestViewModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            var db = new ApplicationDbContext();

            string allowed = "abcdefghijklmnopqrstuvwxyz_0123456789";

            var c = new Contest();

            c.Name = model.Name;
            c.Description = model.Description;
            c.StartedAt = DateTime.Now;
            c.EndsAt = model.EndDate;
            c.VideoId = model.VideoId;
            string id = c.Name.ToLower() + "_" + db.Contests.Count();
            foreach (char ch in id.ToCharArray())
                if (!allowed.Contains(ch))
                    id = id.Replace(ch, '_');
            c.Id = id;
            c.CodepointReward1st = model.GoldReward;
            c.CodepointReward2nd = model.SilverReward;
            c.CodepointReward3rd = model.BronzeReward;
            db.Contests.Add(c);
            db.SaveChanges();

            return RedirectToAction("ViewContest", new { id = c.Id });
        }
    }
}