﻿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.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using HuaGong.Models;
using HuaGong.Repositories;
using HuaGong.Utils;

namespace HuaGong.Controllers
{
    public class LinkagesController : ApiController
    {
        IRepository<int, Linkage> repository;
        IPointRepository pointRepository;

        public LinkagesController(
            IRepository<int, Linkage> repository,
            IPointRepository pointRepository)
        {
            this.repository = repository;
            this.pointRepository = pointRepository;
        }

        // GET: api/linkages
        public IHttpActionResult GetLinkages()
        {
            var errResult = TextHelper.CheckAuthorized(Request);
            if (errResult != null)
                return errResult;

            Pager pager = null;
            string strPageIndex = HttpContext.Current.Request.Params["PageIndex"];
            string strPageSize = HttpContext.Current.Request.Params["PageSize"];
            IEnumerable<Linkage> linkages;

            if (strPageIndex == null || strPageSize == null)
            {
                pager = new Pager();
                linkages = this.repository.GetAll().OrderBy(u => u.ID);
            }
            else
            {
                // 获取分页数据
                int pageIndex = Convert.ToInt32(strPageIndex);
                int pageSize = Convert.ToInt32(strPageSize);
                pager = new Pager(pageIndex, pageSize, this.repository.GetCount());
                linkages = this.repository.GetPagerItems(pageIndex, pageSize, u => u.ID, false);
            }

            List<TempLinkage> items = new List<TempLinkage>();
            foreach (var linkage in linkages)
            {
                TempLinkage item = new TempLinkage();
                item.ID = linkage.ID;
                item.MasterPointID = linkage.MasterPointID;
                item.MasterPointName = this.pointRepository.GetByID(linkage.MasterPointID).ItemName;
                item.SlavePointID = linkage.SlavePointID;
                item.SlavePointName = this.pointRepository.GetByID(linkage.SlavePointID).ItemName;
                item.Type = linkage.Type;
                item.CreateTime = linkage.CreateTime;
                item.Remark = linkage.Remark;
                items.Add(item);
            }
            pager.Items = items;

            return Ok(pager);
        }

        // GET: api/linkages/1
        [ResponseType(typeof(Linkage))]
        public async Task<IHttpActionResult> GetLinkage(int id)
        {
            var errResult = TextHelper.CheckAuthorized(Request);
            if (errResult != null)
                return errResult;

            Linkage item = await this.repository.GetByIdAsync(id);
            if (item == null)
                return NotFound();

            var result = new TempLinkage
            {
                ID = item.ID,
                MasterPointID = item.MasterPointID,
                MasterPointName = this.pointRepository.GetByID(item.MasterPointID).ItemName,
                SlavePointID = item.SlavePointID,
                SlavePointName = this.pointRepository.GetByID(item.SlavePointID).ItemName,
                Type = item.Type,
                CreateTime = item.CreateTime,
                Remark = item.Remark
            };

            return Ok(result);
        }

        // PUT: api/linkages/1
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutLinkage(int id, [FromBody]Linkage linkage)
        {
            var errResult = TextHelper.CheckAuthorized(Request);
            if (errResult != null)
                return errResult;

            if (id != linkage.ID)
                return BadRequest();

            try
            {
                await this.repository.PutAsync(linkage);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                if (!this.repository.IsExist(id))
                    return NotFound();
                else
                    return InternalServerError(ex);
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/linkages
        [ResponseType(typeof(Linkage))]
        public async Task<IHttpActionResult> PostLinkage([FromBody]Linkage linkage)
        {
            var errResult = TextHelper.CheckAuthorized(Request);
            if (errResult != null)
                return errResult;

            try
            {
                linkage.CreateTime = DateTime.Now;
                await this.repository.AddAsync(linkage);
            }
            catch (DbUpdateException ex)
            {
                if (this.repository.IsExist(linkage.ID))
                    return Conflict();
                else
                    return InternalServerError(ex);
            }

            return Ok();
        }

        // DELETE: api/linkages/1
        public async Task<IHttpActionResult> DeleteLinkage(int id)
        {
            var errResult = TextHelper.CheckAuthorized(Request);
            if (errResult != null)
                return errResult;

            Linkage linkage = await this.repository.GetByIdAsync(id);
            if (linkage == null)
                return NotFound();

            await this.repository.DeleteAsync(linkage);

            return Ok();
        }

        private class TempLinkage
        {
            public int ID { get; set; }
            public int MasterPointID { get; set; }
            public string MasterPointName { get; set; }
            public int SlavePointID { get; set; }
            public string SlavePointName { get; set; }
            public int Type { get; set; }
            public DateTime? CreateTime { get; set; }
            public string Remark { get; set; }
        }
    }
}