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;
using System.Diagnostics;

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

        //
        // GET: /Result/

        public ActionResult Index()
        {
            var results = db.Results.Include(r => r.homeClub).Include(r => r.visitorClub).Include(r => r.category);
            return View(results.ToList());
        }

        //
        // GET: /Result/Livesport

        public ActionResult Livesport()
        {
            return View();
        }

        //
        // GET: /Result/Sheet
        [Authorize(Roles = "admin, editor, redaktor, sefredaktor")]
        public ActionResult Sheet(int id = 0, int clubID = 0)
        {
            Result result = db.Results.Find(id);
            List<PlayerResult> playersResult = db.PlayerResults.Where(p => p.resultID == id && p.clubID == clubID).ToList();

            for (var i = playersResult.Count + 1; i <= 16; i++)
            {
                playersResult.Add(new PlayerResult { id = 0, resultID = id, playerID = 0, clubID = clubID, goals = 0, goalsReceived = 0, minutes = 0, redCards = 0, yellowCards = 0 });
            }

            ViewBag.playerID = new SelectList(db.Players.Where(p => p.clubID == clubID).OrderBy(p => p.lastName).ToList()
                .Select(p => new SelectListItem { Value = p.id.ToString(), Text = p.lastName + " " + p.firstName }), "Value", "Text");

            return View(playersResult);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Sheet(List<PlayerResult> playersResult)
        {

            if (ModelState.IsValid)
            {
                foreach (var player in playersResult)
                {

                    if (player.id == 0 && player.playerID > 0)
                    {
                        db.PlayerResults.Add(player);

                    }
                    else if (player.id > 0 && player.playerID > 0)
                    {
                        db.Entry(player).State = EntityState.Modified;
                    }
                    else if (player.id > 0 && player.playerID == 0)
                    {
                        PlayerResult result = db.PlayerResults.Find(player.id);
                        db.PlayerResults.Remove(result);
                    }

                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }

            ViewBag.playerID = new SelectList(db.Players.OrderBy(p => p.lastName).ToList()
                  .Select(p => new SelectListItem { Value = p.id.ToString(), Text = p.lastName + " " + p.firstName }), "Value", "Text");

            return View(playersResult);
        }

        //
        // GET: /Result/Table

        public ActionResult Table(int categoryID)
        {
            List<Club> clubs = db.Clubs.Where(c => c.categoryID == categoryID).ToList();
            List<TableResult> tableResult = new List<TableResult>();
            
            foreach (Club club in clubs) {

                TableResult clubResult = new TableResult();
                clubResult.clubId = club.id;
                clubResult.clubName = club.name;
                clubResult.wins = 0;
                clubResult.draws = 0;
                clubResult.losts = 0;
                clubResult.homeGoals = 0;
                clubResult.awayGoals = 0;
                clubResult.points = 0;
                clubResult.matches = 0;

                List<Result> results = db.Results.Where(r => r.homeClubID == club.id || r.visitorClubID == club.id).ToList();

                foreach (Result result in results)
                {
                    clubResult.matches++;

                    if (result.homeClubID == club.id)
                    {
                        clubResult.points += result.homeClubPoints;

                        clubResult.homeGoals += result.homeClubGoals;
                        clubResult.awayGoals += result.visitorClubGoals;

                        if (result.homeClubGoals > result.visitorClubGoals)
                        {
                            clubResult.wins++;
                        }
                        else if (result.homeClubGoals < result.visitorClubGoals)
                        {
                            clubResult.losts++;
                        }
                        else
                        {
                            clubResult.draws++;
                        }

                    } else if (result.visitorClubID == club.id) {
                        clubResult.points += result.visitorClubPoints;

                        clubResult.homeGoals += result.visitorClubGoals;
                        clubResult.awayGoals += result.homeClubGoals;

                        if (result.homeClubGoals > result.visitorClubGoals)
                        {
                            clubResult.losts++;
                        }
                        else if (result.homeClubGoals < result.visitorClubGoals)
                        {
                            clubResult.wins++;
                        }
                        else
                        {
                            clubResult.draws++;
                        }
                    }
                }

                tableResult.Add(clubResult);
            }

            ViewBag.clubs = tableResult.OrderByDescending(r => r.points).ThenByDescending(r => r.matches).ThenBy(r => r.clubName);
            return View();

        }

        //
        // GET: /Result/Details/5

        public ActionResult Details(int id = 0)
        {
            Result result = db.Results.Find(id);
            if (result == null)
            {
                return HttpNotFound();
            }
            return View(result);
        }

        //
        // GET: /Result/Create
        [Authorize(Roles = "admin, editor, redaktor, sefredaktor")]
        public ActionResult Create()
        {
            ViewBag.homeClubID = new SelectList(db.Clubs, "id", "name");
            ViewBag.visitorClubID = new SelectList(db.Clubs, "id", "name");
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name");
            return View();
        }

        //
        // POST: /Result/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Result result)
        {
            if (ModelState.IsValid)
            {

                if (result.homeClubGoals > result.visitorClubGoals)
                {
                    result.homeClubPoints = 3;
                    result.visitorClubPoints = 0;
                }
                else if (result.homeClubGoals < result.visitorClubGoals)
                {
                    result.homeClubPoints = 0;
                    result.visitorClubPoints = 3;
                }
                else
                {
                    result.homeClubPoints = 1;
                    result.visitorClubPoints = 1;
                }

                db.Results.Add(result);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.homeClubID = new SelectList(db.Clubs, "id", "name", result.homeClubID);
            ViewBag.visitorClubID = new SelectList(db.Clubs, "id", "name", result.visitorClubID);
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name", result.categoryID);
            return View(result);
        }

        //
        // GET: /Result/Edit/5
        [Authorize(Roles = "admin, editor, redaktor, sefredaktor")]
        public ActionResult Edit(int id = 0)
        {
            Result result = db.Results.Find(id);
            if (result == null)
            {
                return HttpNotFound();
            }
            ViewBag.homeClubID = new SelectList(db.Clubs, "id", "name", result.homeClubID);
            ViewBag.visitorClubID = new SelectList(db.Clubs, "id", "name", result.visitorClubID);
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name", result.categoryID);
            return View(result);
        }

        //
        // POST: /Result/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Result result)
        {
            if (ModelState.IsValid)
            {

                if (result.homeClubGoals > result.visitorClubGoals)
                {
                    result.homeClubPoints = 3;
                    result.visitorClubPoints = 0;
                }
                else if (result.homeClubGoals < result.visitorClubGoals)
                {
                    result.homeClubPoints = 0;
                    result.visitorClubPoints = 3;
                }
                else
                {
                    result.homeClubPoints = 1;
                    result.visitorClubPoints = 1;
                }

                db.Entry(result).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.homeClubID = new SelectList(db.Clubs, "id", "name", result.homeClubID);
            ViewBag.visitorClubID = new SelectList(db.Clubs, "id", "name", result.visitorClubID);
            ViewBag.categoryID = new SelectList(db.Categories, "id", "name", result.categoryID);
            return View(result);
        }

        //
        // GET: /Result/Delete/5
        [Authorize(Roles = "admin, editor, redaktor, sefredaktor")]
        public ActionResult Delete(int id = 0)
        {
            Result result = db.Results.Find(id);
            if (result == null)
            {
                return HttpNotFound();
            }
            return View(result);
        }

        //
        // POST: /Result/Delete/5

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

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