﻿using System;
using Microsoft.AspNetCore.Mvc;
using Snooker.Api.Persistence;
using System.Linq;
using Snooker.Api.Models;
using System.Threading.Tasks;

namespace Snooker.API.Controllers
{
    [Route("[controller]")]
    public class PlayerController
    {
		private IPlayerRepository _playerRepository;

		public PlayerController(IPlayerRepository playerRepository)
		{
            if (playerRepository == null)
            {
                throw new ArgumentException(nameof(playerRepository));
            }

            _playerRepository = playerRepository;
		}

		[HttpGet]
		public async Task<IActionResult> Get([FromQuery]long seasonId, [FromQuery]long leagueId,[FromQuery]long? playerId)
		{
			return new OkObjectResult(await _playerRepository.GetPlayers(seasonId, leagueId, playerId));
		}

		[HttpGet("log")]
		public async Task<IActionResult> GetLogs([FromQuery]long seasonId, [FromQuery]long leagueId, [FromQuery]int? round)
		{
			return new OkObjectResult(await _playerRepository.GetPlayerLog(seasonId, leagueId, round));
		}

        [HttpGet("scores")]
		public async Task<IActionResult> GetScores([FromQuery]long seasonId, [FromQuery]long leagueId, [FromQuery]int round)
        {
            var players = (await _playerRepository.GetPlayers(seasonId, leagueId)).OrderBy(key => key.Id).ToList();
			var playerScores = await _playerRepository.GetPlayerScores(seasonId, leagueId, round);
			var scoreMatrix = new string[players.Count() + 1, players.Count() + 1];

			//TODO clean up
			//set column and row headers
			for (int i = 0; i < players.Count(); i++)
			{
				scoreMatrix[0, i + 1] = players[i].Name;
				scoreMatrix[i + 1, 0] = players[i].Name;
			}

			for (int row = 1; row < players.Count() + 1; row++)
			{
				var rowPlayer = players[row - 1];

				for (int column = 1; column < players.Count() + 1; column++)
				{
					var columnPlayer = players[column - 1];
					string score = string.Empty;

					if (rowPlayer != columnPlayer)
					{
						var matchResult = playerScores.FirstOrDefault(m => (m.HomePlayerId == rowPlayer.Id && m.AwayPlayerId == columnPlayer.Id) ||
																	(m.HomePlayerId == columnPlayer.Id && m.AwayPlayerId == rowPlayer.Id));

						if (matchResult == null) continue;

						score = matchResult.HomePlayerId == rowPlayer.Id
										   ? matchResult.HomePlayerScore.ToString()
										   : matchResult.AwayPlayerScore.ToString();

					}

					scoreMatrix[row, column] = score;
				}
			}

			return new OkObjectResult(new PlayerLog()
			{
				Scores = scoreMatrix
			});
		}
    }
}
