﻿using AuxidyCinema.DTOs;
using AuxidyCinema.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AuxidyCinema.Controllers.API
{
    public class GenreController : ApiController
    {
        private ApplicationDbContext _context;
        public GenreController()
        {
            _context = new ApplicationDbContext();
        }
        //get /API/Genre
        [HttpGet]
        public IHttpActionResult GetGernes(string query = null)
        {
            IQueryable<Genre> GenreQuery = _context.Genres;
            if (!String.IsNullOrWhiteSpace(query))
            {
                GenreQuery = GenreQuery.Where(x => x.genreName.Contains(query));
            }
            var GenreDTO = GenreQuery.ToList().Select(AutoMapper.Mapper.Map<Genre, GenreDTO>);
            return Ok(GenreDTO);
        }
        [HttpGet]
        public IHttpActionResult GetGenres(int ID)
        {
            var Genre = _context.Genres.SingleOrDefault(x => x.genreID == ID);
            if (Genre == null)
            {
                NotFound();
            }
            return Ok(AutoMapper.Mapper.Map<Genre, GenreDTO>(Genre));
        }
        [HttpPost]
        public IHttpActionResult CreateGenre(GenreDTO GenrerDTO)
        {
            if (!ModelState.IsValid)
            {
                BadRequest();
            }
            var Genre = AutoMapper.Mapper.Map<GenreDTO, Genre>(GenrerDTO);
            _context.Genres.Add(Genre);
            _context.SaveChanges();
            GenrerDTO.genreID = Genre.genreID;
            return Created(new Uri(Request.RequestUri + "/" + Genre.genreID), GenrerDTO);
        }
        [HttpPut]
        public void UpdateCustomer(int id, GenreDTO genreDTO)
        {

            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            var GenreinDB = _context.Genres.SingleOrDefault(c => c.genreID == id);

            if (GenreinDB == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);

            }
            AutoMapper.Mapper.Map(genreDTO, GenreinDB);
            _context.SaveChanges();
        }
        [HttpDelete]
        public void DeleteCustomer(int Id)
        {
            var GenreinDB = _context.Genres.SingleOrDefault(x => x.genreID == Id);

            if (GenreinDB == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _context.Genres.Remove(GenreinDB);
            _context.SaveChanges();
        }
    }
}
