using Fast.Models;

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

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

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

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

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

            itemsQueryable = (
                from q in db.Holidays
                select new HolidayListItem
                {
                    HolidayId = q.Id,
                    Date = q.HolidayDate,
                    Holiday = q.HolidayName ?? "",
                    HolidayScheduleName = q.HolidaySchedule.Schedule
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

        [Permission("Holiday", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetRequiredData()
        {
            var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Holiday", PermissionType.Modify);
            var schedules = await (from q in db.HolidaySchedules select new IdName(q.Id, q.Schedule)).ToListAsync();

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

        [Permission("Holiday", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.Holidays
                where q.Id == id
                select new HolidayDetail
                {
                    HolidayId = q.Id,
                    HolidayDate = q.HolidayDate,
                    HolidayName = q.HolidayName ?? "",
                    HolidayScheduleId = q.HolidayScheduleId
                }
            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }

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

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

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

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

                var d = detail;
                dbItem.HolidayName = d.HolidayName;
                dbItem.HolidayDate = d.HolidayDate;
                dbItem.IsWeekend = d.HolidayDate?.DayOfWeek == DayOfWeek.Saturday || d.HolidayDate?.DayOfWeek == DayOfWeek.Sunday;
                dbItem.HolidayScheduleId = d.HolidayScheduleId;
                await db.SaveChangesAsync();
                resultId = dbItem.Id;

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
