using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TriathlonRaceTracking.Data;
using TriathlonRaceTracking.Models;

namespace TriathlonRaceTracking.Controllers
{
    [Produces("application/json")]
    [Route("api/Timings")]
    public class TimingsController : Controller
    {
        private readonly TriathlonRaceTrackingContext _context;

        public TimingsController(TriathlonRaceTrackingContext context)
        {
            _context = context;
        }


        // GET: api/Timings/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetTiming([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var timing = await _context.Timings.SingleOrDefaultAsync(m => m.ID == id);

            if (timing == null)
            {
                return NotFound();
            }

            return Ok(timing);
        }

        // POST: api/Timings
        [HttpPost]
        public async Task<IActionResult> PostTiming([FromBody] TimingPostModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var registration = _context.Registrations.SingleOrDefault(r => r.BibNumber == model.BibNumber && r.RaceID == model.RaceId);
            var timingPoint = _context.TimingPoints.SingleOrDefault(tp => tp.Code.Equals(model.TPCode) && tp.RaceID == model.RaceId);

            var timing = new Timing
            {
                RegistrationID=registration.ID,
                TimingPointID=timingPoint.ID,
                Time=model.Time
            };

            _context.Timings.Add(timing);
            _context.SaveChangesAsync().Wait();

            return CreatedAtAction("GetTiming", new { id = timing.ID }, timing);
        }

    }

    public class TimingPostModel
    {
        public int BibNumber { get; set; }
        public int RaceId { get; set; }
        public string TPCode { get; set; }
        public DateTime Time { get; set; }
    }
}