
namespace Fast.Controllers;


[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MeterCommonController : ODataController
{
    private readonly MyDbContext db;
    private readonly AuthorizationHelper authHelper;
    public MeterCommonController(MyDbContext context)
    {
        db = context;
        authHelper = new AuthorizationHelper(Main.IsAuthenticationEnabled);
    }

    [Permission("Meter", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetRequiredData()
    {
        var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Meter", PermissionType.Modify);
        var stateNames = await DataHelper.GetTerritoriesAsync();
        var counties = await db.Counties.Select(x => new { countyId = x.Id, CountyName = x.Name, StateName = x.State.Name, x.StateId }).ToListAsync();
        var producers = await DataHelper.GetProducersAsync(false);
        var blocks = await DataHelper.GetLeasesAsync();
        var locations = await (from q in db.Locations orderby q.Name select new IdName(q.Id, q.Name ?? "")).ToListAsync();

        var result = new { hasModifyPermission, stateNames, counties, blocks, locations, producers };
        return Ok(result);
    }

    [Permission("Meter", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetDetail(int MeterId)
    {
        var dbItem = await (
            from q in db.Meters
            where q.Id == MeterId
            select new
            {
                MeterId = q.Id,
                Name = q.Name,
                InactiveDate = q.InactiveDate,
                StateId = q.StateId,
                CountyId = q.CountyId,
                LocationId = q.LocationId,
                LeaseId = q.LeaseId,
                Latitude = q.Latitude,
                Longitude = q.Longitude,
                ProducerIds = q.ProducerIds,
            }
        ).AsNoTracking().FirstOrDefaultAsync();


        var detail = new MeterCommonDetail
        {
            MeterId = dbItem!.MeterId,
            Name = dbItem.Name,
            InactiveDate = dbItem.InactiveDate,
            StateId = dbItem.StateId,
            CountyId = dbItem.CountyId,
            LocationId = dbItem.LocationId,
            LeaseId = dbItem.LeaseId,
            Latitude = dbItem.Latitude,
            Longitude = dbItem.Longitude,
            ProducerIds = dbItem.ProducerIds != null ? dbItem.ProducerIds.Split(",").Select(x => int.Parse(x)).ToList() : null,
        };

        return Ok(detail);
    }


}
