using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using wispro.sp.entity;
using wispro.sp.share;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace wispro.sp.api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BasePointRuleController : ControllerBase
    {
        spDbContext Context;
        public BasePointRuleController(spDbContext context)
        {
            Context = context;
        }
        // GET: api/<BasePointRuleController>
        [HttpGet]
        public IEnumerable<BasePointRule> Get()
        {

            return Context.BasePointRules.ToList<BasePointRule>();
        }

        
        [HttpGet("{id}")]
        public BasePointRule Get(int id)
        {
            return Context.BasePointRules.Where<BasePointRule>(b => b.Id == id).FirstOrDefault<BasePointRule>();
        }

        // POST api/<BasePointRuleController>
        [HttpPost]
        public ApiSaveResponse New(BasePointRule value)
        {
            ApiSaveResponse ret = new ApiSaveResponse();

            try
            {
                Context.BasePointRules.Add(value);
                Context.SaveChanges();
                ret.Success = true;
            }
            catch(Exception ex)
            {
                ret.Success = false;
                ret.ErrorMessage = ex.Message;
            }

            return ret;
        }

        
        [HttpPost]
        public void Update(int id, string field,string value)
        {
            string strSQL = $"update basepointrule set {field}={value} where id={id}";
            Context.Database.ExecuteSqlRaw(strSQL);
        }

        
        [HttpDelete("{id}")]
        public bool Delete(int id)
        {
            Context.BasePointRules.Remove(new BasePointRule() { Id = id });
            Context.SaveChanges();
            return true;
        }
    }
}
