using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;

namespace rockfishCore.Controllers
{
    [Produces("application/json")]
    [Route("api/Site")]
    [Authorize]
    public class SiteController : Controller
    {
        private readonly rockfishContext _context;

        public SiteController(rockfishContext context)
        {
            _context = context;
        }


        //Get api/site/77/purchases
        [HttpGet("{id}/purchases")]
        public IEnumerable<Purchase> GetPurchases([FromRoute] long id)
        {
            var l = _context.Purchase
                 .Where(b => b.SiteId.Equals(id))
                 .OrderByDescending(b => b.PurchaseDate)
                 .ToList();
            return l;
        }

        //  //Get api/site/77/activepurchases
        // [HttpGet("{id}/activepurchases")]
        // public IEnumerable<Purchase> GetActivePurchases([FromRoute] long id)
        // {
        //     var l = _context.Purchase
        //          .Where(b => b.SiteId.Equals(id))
        //          .Where(b => b.CancelDate==null)
        //          .OrderByDescending(b => b.PurchaseDate)
        //          .ToList();
        //     return l;
        // }

         //Get api/site/77/activepurchases
        [HttpGet("{id}/activepurchases")]
        public IEnumerable<dtoNameIdItem> GetActivePurchases([FromRoute] long id)
        {
            var res = from c in _context.Purchase
            .Where(c => c.SiteId.Equals(id))
            .Where(c => c.CancelDate==null)
            .OrderByDescending(c => c.PurchaseDate)
                      select new dtoNameIdItem
                      {                         
                          id = c.Id,
                          name = c.Name
                      };
            return res.ToList();
        }

        // //Get api/site/77/incidents
        // [HttpGet("{id}/incidents")]
        // public IEnumerable<Incident> GetIncidents([FromRoute] long id)
        // {
        //     var l = _context.Incident
        //          .Where(b => b.SiteId.Equals(id))
        //          .OrderByDescending(b => b.Id)//no single suitable date to order by
        //          .ToList();
        //     return l;
        // }


        // //Get api/site/77/trials
        // [HttpGet("{id}/trials")]
        // public IEnumerable<Trial> GetTrials([FromRoute] long id)
        // {
        //     var l = _context.Trial
        //          .Where(b => b.SiteId.Equals(id))
        //          .OrderByDescending(b => b.Id)
        //          .ToList();
        //     return l;
        // }

        //Get api/site/77/name
        [HttpGet("{id}/name")]
        public async Task<IActionResult> GetName([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var ret = await _context.Site
            .Select(r => new { r.Id, r.Name, r.CustomerId })
                           .Where(r => r.Id == id)
                           .FirstAsync();
            return Ok(ret);
        }



        // GET: api/Site
        [HttpGet]
        public IEnumerable<Site> GetSite()
        {
            return _context.Site;
        }

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

            var site = await _context.Site.SingleOrDefaultAsync(m => m.Id == id);

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

            return Ok(site);
        }

        // PUT: api/Site/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutSite([FromRoute] long id, [FromBody] Site site)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != site.Id)
            {
                return BadRequest();
            }

            _context.Entry(site).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SiteExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Site
        [HttpPost]
        public async Task<IActionResult> PostSite([FromBody] Site site)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.Site.Add(site);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetSite", new { id = site.Id }, site);
        }

        // DELETE: api/Site/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteSite([FromRoute] long id)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }


            var site = await _context.Site.SingleOrDefaultAsync(m => m.Id == id);

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


            _context.Site.Remove(site);
            await _context.SaveChangesAsync();

            return Ok(site);
        }

        private bool SiteExists(long id)
        {
            return _context.Site.Any(e => e.Id == id);
        }
    }
}