﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using StudentManagement.Models;
using StudentManagement.Dtos;
using AutoMapper;
using System.Data.Entity;

namespace StudentManagement.Controllers.Api
{
    public class StudentsController : ApiController
    {
        ApplicationDbContext _context;

        public StudentsController()
        {
            _context = new ApplicationDbContext();
        }

        // GET /api/students
        public IHttpActionResult GetStudents()
        {
            var studentDtos = _context.Students
                .Include(c => c.Classroom)
                .ToList()
                .Select(Mapper.Map<Students, StudentDto>);

            return Ok(studentDtos);
        }

        // GET /api/students/1
        public IHttpActionResult GetStudent(int id)
        {
            var student = _context.Students.SingleOrDefault(s => s.Id == id);

            if (student == null)
                return NotFound();

            return Ok(Mapper.Map<Students, StudentDto>(student));
        }


        // POST /api/students
        [HttpPost]
        public IHttpActionResult CreateStudent(StudentDto studentDto)
        {
            if (!ModelState.IsValid)
                return BadRequest();


            var student = Mapper.Map<StudentDto, Students>(studentDto);

            _context.Students.Add(student);
            _context.SaveChanges();

            studentDto.Id = student.Id;

            return Created(new Uri(Request.RequestUri + "/" + student.Id), studentDto);
        }

        // PUT /api/students/1
        [HttpPut]
        public IHttpActionResult UpdateStudent(int id, StudentDto studentDto)
        {
            if (studentDto == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            var studentInDb = _context.Students.SingleOrDefault(s => s.Id == id);

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


            Mapper.Map(studentDto, studentInDb);
            _context.SaveChanges();

            studentDto.Id = studentInDb.Id;

            return Created(new Uri(Request.RequestUri + "/" + studentInDb.Id), studentDto);
        }


        // DELETE /api/delete/1
        [HttpDelete]
        public void DeleteStudent(int id)
        {
            var studentInDb = _context.Students.SingleOrDefault(s => s.Id == id);

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

            _context.Students.Remove(studentInDb);
            _context.SaveChanges();

           
        }


    }
}
