
namespace Fast.Web.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class PlantStatementPricesController : ODataController
    {
        private readonly MyDbContext db;

        private readonly AuthorizationHelper authHelper;
        public PlantStatementPricesController(MyDbContext context, IConfiguration configuration)
        {
            db = context;
            authHelper = new AuthorizationHelper(Main.IsAuthenticationEnabled);
        }

        [Permission("Plant Statement Prices", PermissionType.View)]
        [Route("/odata/GetPlantStatementPricesItems")]
        public IActionResult GetItems(ODataQueryOptions<PlantStatementPricesListItem> queryOptions, bool isExport)
        {
            queryOptions = Util.GetQueryOptionsWithConvertedDates(queryOptions);
            var itemsQueryable = GetItemsInternal();
            var items = (queryOptions.ApplyTo(itemsQueryable) as IEnumerable<PlantStatementPricesListItem>)?.ToList();

            if (isExport)
                return File(Util.Excel.GetExportFileStream(items), "application/octet-stream");
            else
                return Ok(items);
        }

        [Permission("Plant Statement Prices", PermissionType.View)]
        [Route("[action]")]
        public IQueryable<PlantStatementPricesListItem> GetItemsInternal()
        {
            IQueryable<PlantStatementPricesListItem>? itemsQueryable = null;

            itemsQueryable = (
                from q in db.PlantStatementPrices
                select new PlantStatementPricesListItem
                {
                    Id = q.Id,
                    Name = q.Name,
                    ProductionMonth = q.ProductionMonth,
                    StatementDate = q.StatementDate,
                    Plant = q.Plant.Name,
                    Producer = q.Producer.Name,
                    PropanePrice = q.PropanePrice,
                    EthanePrice = q.EthanePrice,
                    NormalButanePrice = q.NormalButanePrice,
                    IsoButanePrice = q.IsoButanePrice,
                    NaturalGasolinePrice = q.NaturalGasolinePrice,
                    ScrubberPrice = q.ScrubberPrice
                }

            ).AsNoTracking();

            return itemsQueryable;
        }



        [Permission("Plant Statement Prices", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetRequiredData()
        {
            var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Plant Statement Prices", PermissionType.Modify);

            var plants = await (from q in db.Plants orderby q.Name select new { q.Id, q.Name }).ToListAsync();
            var producers = (await DataHelper.GetProducersAsync(false));
            var pricesNames = await (from q in db.PlantStatementPrices orderby q.Name select new { q.Name }).Distinct().ToListAsync();
            var result = new { hasModifyPermission, plants, producers, pricesNames };

            return Ok(result);
        }

        [Permission("Plant Statement Prices", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.PlantStatementPrices
                where q.Id == id
                select new PlantStatementPricesDetail
                {
                    Id = q.Id,
                    Name = q.Name,
                    ProductionMonth = q.ProductionMonth,
                    StatementDate = q.StatementDate,
                    PlantId = q.Plant.Id,
                    ProducerId = q.Producer.Id,
                    PropanePrice = q.PropanePrice,
                    EthanePrice = q.EthanePrice,
                    NormalButanePrice = q.NormalButanePrice,
                    IsoButanePrice = q.IsoButanePrice,
                    NaturalGasolinePrice = q.NaturalGasolinePrice,
                    ScrubberPrice = q.ScrubberPrice
                }


            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }


        [Permission("Plant Statement Prices", PermissionType.Modify)]
        [Route("SaveDetail")]
        public async Task<IActionResult> SaveDetail(PlantStatementPricesDetail detail, Enums.SaveType saveType)
        {
            int resultId = 0;
            detail.ProductionMonth = Util.Date.FirstDayOfMonth(detail.ProductionMonth);
            await db.Database.CreateExecutionStrategy().Execute(async () =>
            {
                using var dbContextTransaction = await db.Database.BeginTransactionAsync();
                PlantStatementPrice? dbItem = null;
                if (saveType != Enums.SaveType.New)
                {
                    dbItem = await (
                        from q in db.PlantStatementPrices
                        where q.Id == detail.Id
                        select q
                    ).FirstOrDefaultAsync();
                }

                if (dbItem == null) //if the item does not exist then add it
                {
                    dbItem = new PlantStatementPrice();

                    db.PlantStatementPrices.Add(dbItem);
                }
                else
                {
                    //remove existing items so that they get completely re-inserted
                }

                var d = detail;

                dbItem.Name = d.Name;
                dbItem.ProductionMonth = d.ProductionMonth;
                dbItem.StatementDate = d.StatementDate;
                dbItem.PlantId = d.PlantId;
                dbItem.ProducerId = d.ProducerId;
                dbItem.PropanePrice = d.PropanePrice;
                dbItem.EthanePrice = d.EthanePrice;
                dbItem.NormalButanePrice = d.NormalButanePrice;
                dbItem.IsoButanePrice = d.IsoButanePrice;
                dbItem.NaturalGasolinePrice = d.NaturalGasolinePrice;
                dbItem.ScrubberPrice = d.ScrubberPrice;



                await db.SaveChangesAsync();
                resultId = dbItem.Id;

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

        [Permission("Plant Statement Prices", PermissionType.Modify)]
        [Route("[action]/{id}")]
        public IActionResult DeleteDetail(int Id)
        {
            var plantStatementPrices = db.PlantStatementPrices.Where(x => x.Id == Id).FirstOrDefault();

            if (plantStatementPrices == null)
                return NotFound();
            else

                db.Entry(plantStatementPrices).State = EntityState.Deleted;
            db.SaveChanges();

            return Ok();
        }
    }
}
