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

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

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

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

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

            itemsQueryable = (
                from q in db.Counties
                select new CountyListItem
                {
                    Id = q.Id,
                    CountyName = q.Name ?? "",
                    StateId = q.StateId,
                    StateName = q.State.Name ?? "",

                }
            ).AsNoTracking();

            return itemsQueryable;
        }

        [Permission("County", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetRequiredData()
        {
            var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "County", PermissionType.Modify);
            var counties = await db.Counties.Select(x => new { x.Id, CountyName = x.Name, x.StateId }).ToListAsync();
            var states = await DataHelper.GetTerritoriesAsync();
            var result = new { hasModifyPermission, counties, states };
            return Ok(result);
        }

        [Permission("County", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.Counties
                where q.Id == id
                select new CountyDetail
                {
                    Id = q.Id,
                    CountyName = q.Name ?? "",
                    StateId = q.StateId,


                }
            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }

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

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

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

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

                var d = detail;
                dbItem.Name = d.CountyName;
                dbItem.StateId = d.StateId;

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

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
