using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FotbalPortal.Models;
using FotbalPortal.DAL;

namespace FotbalPortal.Controllers
{
    public class ClubController : Controller
    {
        private PortalContext db = new PortalContext();

        //
        // GET: /Club/

        public ActionResult Index()
        {
            var clubs = db.Clubs.Include(c => c.country).Include(c => c.stadium).Include(c => c.category);
            return View(clubs.ToList());
        }

        //
        // GET: /Club/Details/5

        public ActionResult Details(int id = 0)
        {
            Club club = db.Clubs.Find(id);
            if (club == null)
            {
                return HttpNotFound();
            }

            ViewBag.favorite = false;

            var userId = (int)WebMatrix.WebData.WebSecurity.CurrentUserId;

            if (db.FavoriteClubs.Where(c => c.clubID == id).Where(c => c.userID == userId).ToArray().Count() > 0)
            {
                ViewBag.favorite = true;
            }

            return View(club);
        }

        //
        // GET: /Club/Team/5

        public ActionResult Team(int id = 0)
        {
            Club club = db.Clubs.Find(id);
            if (club == null)
            {
                return HttpNotFound();
            }

            List<Player> players = db.Players.Where(p => p.clubID == club.id).OrderBy(p => p.dressNumber).ToList();

            List<SquadPlayer> squad = new List<SquadPlayer>();

            foreach (Player player in players)
            {
                SquadPlayer _player = new SquadPlayer { playerID = player.id, name = player.lastName + " " + player.firstName, born = player.borned.ToString("dd.MM.yyyy"), matches = 0, minutes = 0, goals = 0, number = player.dressNumber, redCards = 0, yellowCards = 0 };

                List<PlayerResult> playerResults = db.PlayerResults.Where(p => p.playerID == player.id && p.clubID == club.id).ToList();

                foreach (PlayerResult result in playerResults)
                {
                    _player.minutes += result.minutes;
                    _player.goals += result.goals;
                    _player.yellowCards += result.yellowCards;
                    _player.redCards += result.redCards;

                    if (result.minutes > 0)
                    {
                        _player.matches++;
                    }
                }

                squad.Add(_player);
            }

            ViewBag.squad = squad;

            return View();
        }

        //
        // GET: /Club/Create
        [Authorize(Roles = "admin")]
        public ActionResult Create()
        {
            ViewBag.countryID = new SelectList(db.Countries, "id", "name");
            ViewBag.stadiumID = new SelectList(
                db.Stadiums.ToList()
                .Select(s => new SelectListItem { Value = s.id.ToString(), Text = s.name + ", " + s.address}), "Value", "Text");
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name");
            return View();
        }

        //
        // POST: /Club/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Club club)
        {
            if (ModelState.IsValid)
            {
                db.Clubs.Add(club);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.countryID = new SelectList(db.Countries, "id", "name", club.countryID);
            ViewBag.stadiumID = new SelectList(db.Stadiums, "id", "name", club.stadiumID);
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name", club.categoryID);
            return View(club);
        }

        //
        // GET: /Club/Favorite

        public ActionResult Favorite(int clubId = 0)
        {
            FavoriteClub favoriteClub = new FavoriteClub();
            favoriteClub.clubID = clubId;
            favoriteClub.userID = (int)WebMatrix.WebData.WebSecurity.CurrentUserId;

            db.FavoriteClubs.Add(favoriteClub);
            db.SaveChanges();

            return RedirectToAction("Index", "Club");
        }

        // GET: /Club/Unfavorite

        public ActionResult Unfavorite(int clubId = 0)
        {

            var actualId = (int)WebMatrix.WebData.WebSecurity.CurrentUserId;

            FavoriteClub favoriteClub = db.FavoriteClubs.Where(c => c.userID == actualId).Where(c => c.clubID == clubId).First();

            db.FavoriteClubs.Remove(favoriteClub);
            db.SaveChanges();

            return RedirectToAction("Index", "Club");
        }

        //
        // GET: /Club/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id = 0)
        {
            Club club = db.Clubs.Find(id);
            if (club == null)
            {
                return HttpNotFound();
            }
            ViewBag.countryID = new SelectList(db.Countries, "id", "name", club.countryID);
            ViewBag.stadiumID = new SelectList(
                db.Stadiums.ToList()
                .Select(s => new SelectListItem { Value = s.id.ToString(), Text = s.name + ", " + s.address }), "Value", "Text", club.stadiumID);

            ViewBag.categoryID = new SelectList(
                db.Categories, "id", "name", club.categoryID
                );
            
            return View(club);
        }

        //
        // POST: /Club/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Club club)
        {
            if (ModelState.IsValid)
            {
                db.Entry(club).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.countryID = new SelectList(db.Countries, "id", "name", club.countryID);
            ViewBag.stadiumID = new SelectList(db.Stadiums, "id", "name", club.stadiumID);
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name", club.categoryID);
            return View(club);
        }

        //
        // GET: /Club/Delete/5
        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id = 0)
        {
            Club club = db.Clubs.Find(id);
            if (club == null)
            {
                return HttpNotFound();
            }
            return View(club);
        }

        //
        // POST: /Club/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Club club = db.Clubs.Find(id);
            db.Clubs.Remove(club);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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