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

        public PipelineController(MyDbContext context)
        {
            db = context;
            authHelper = new AuthorizationHelper(Main.IsAuthenticationEnabled);
        }

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

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

        [Permission("Pipeline", PermissionType.View)]
        [Route("[action]")]
        public IQueryable<PipelineListItem> GetItemsInternal()
        {
            IQueryable<PipelineListItem>? itemsQueryable = null;

            itemsQueryable = (
                from q in db.VwPipelineOverviewInfos
                join p in db.Pipelines on q.PipeId equals p.Id
                select new PipelineListItem
                {
                    PipelineId = q.PipeId!.Value,
                    FullName = q.PipeName ?? "",
                    ShortName = q.PipeShort ?? "",
                    PipeCode = q.PipeCode ?? "",
                    Products = q.Commodities ?? "",
                    PipelineClassification = p.PipelineType.Name ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

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

            var products = await DataHelper.GetProductsAsync();
            var pipelineTypes = (from q in db.PipelineTypes select new { q.Id, q.Name }).ToList();

            var result = new { hasModifyPermission, products, pipelineTypes };
            return Ok(result);
        }

        [Permission("Pipeline", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detailTemp = await (
                from q in db.Pipelines
                where q.Id == id
                select new
                {
                    PipelineId = q.Id,
                    FullName = q.Name ?? "",
                    ShortName = q.PipeShort ?? "",
                    PipelineDescription = q.PipelineDescription ?? "",
                    PipeCode = q.PipeCode ?? "",
                    q.PipelineTypeId,
                    q.ProductIds
                }
            ).AsNoTracking().FirstAsync();

            var detail = new PipelineDetail()
            {
                PipelineId = detailTemp.PipelineId,
                FullName = detailTemp.FullName,
                ShortName = detailTemp.ShortName,
                PipelineDescription = detailTemp.PipelineDescription,
                PipelineTypeId = detailTemp.PipelineTypeId,
                PipeCode = detailTemp.PipeCode,
                ProductIds = detailTemp.ProductIds == null ? new List<int>() : detailTemp.ProductIds.Split(",", StringSplitOptions.None).Select(x => int.Parse(x)).ToList()
            };

            return Ok(detail);
        }

        public enum SaveType
        {
            New = 1,
            Normal = 2
        }

        [Permission("Pipeline", PermissionType.Modify)]
        [Route("[action]")]
        public async Task<IActionResult> SaveDetail(PipelineDetail detail, SaveType saveType)
        {
            int resultId = 0;

            await db.Database.CreateExecutionStrategy().Execute(async () =>
            {
                using var dbContextTransaction = await db.Database.BeginTransactionAsync();
                Pipeline? dbItem = null;
                if (saveType != SaveType.New)
                {
                    dbItem = await (
                        from q in db.Pipelines
                        where q.Id == detail.PipelineId
                        select q
                    ).FirstOrDefaultAsync();
                }

                if (dbItem == null) //if the item does not exist then add it
                {
                    dbItem = new Pipeline();
                    db.Pipelines.Add(dbItem);
                }
                else
                {
                    //remove existing items so that they get completely re-inserted
                }

                var d = detail;
                dbItem.Name = d.FullName;
                dbItem.PipeShort = d.ShortName;
                dbItem.PipelineDescription = d.PipelineDescription;
                dbItem.PipelineTypeId = d.PipelineTypeId;
                dbItem.PipeCode = d.PipeCode;
                dbItem.ProductIds = String.Join(",", d.ProductIds.Select(x => x.ToString()).ToList());

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

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

        [Permission("Pipeline", PermissionType.Modify)]
        [Route("[action]/{id}")]
        public async Task<IActionResult> DeleteDetail(int id)
        {
            Pipeline dbItem = await db.Pipelines.Where(x => x.Id == id).FirstAsync();
            db.Pipelines.Remove(dbItem);
            await db.SaveChangesAsync();

            return Ok();
        }
    }
}
