using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace MvcApplication1.Controllers
{
    public class TestController : ApiController
    {
        private jsoEntities db = new jsoEntities();

        // GET api/Test
        public IEnumerable<Test> Get()
        {
            return db.Test.AsEnumerable();
        }

        // GET api/Test/5
        public Test Get(int id)
        {
            Test test = db.Test.Find(id);
            if (test == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return test;
        }

        // PUT api/Test/5
        public HttpResponseMessage Put(int id, Test test)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != test.id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(test).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/Test
        public HttpResponseMessage Post(Test test)
        {
            ModelState.Clear();
            if (ModelState.IsValid)
            {
                db.Test.Add(test);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, test);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = test.id }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // DELETE api/Test/5
        public HttpResponseMessage Delete(int id)
        {
            Test test = db.Test.Find(id);
            if (test == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.Test.Remove(test);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, test);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}