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

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

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

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

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

            itemsQueryable = (
                from q in db.Zones
                select new ZoneListItem
                {
                    ZoneId = q.Id,
                    ZoneName = q.Name,
                    PipeName = q.Pipeline.Name ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

        [Permission("Zone", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetRequiredData()
        {
            var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Zone", PermissionType.Modify);
            var pipelines = (await DataHelper.GetPipelinesAsync(false)).Select(x => new IdName(x.PipeId, x.PipeName));

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

        [Permission("Zone", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.Zones
                where q.Id == id
                select new ZoneDetail
                {
                    ZoneId = q.Id,
                    ZoneName = q.Name,
                    PipelineId = q.PipelineId
                }
            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }

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

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

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

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

                var d = detail;
                dbItem.Name = d.ZoneName;
                dbItem.PipelineId = d.PipelineId;

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

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
