EFB/Controllers/FlightsimController.cs

87 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EFB.Sessions;
using Microsoft.Extensions.Logging;
using EFB.Models;
using EFB.MongoData;
2022-02-18 21:13:21 +00:00
using EFB.Models.Route;
namespace EFB.Controllers
{
//[Route("[controller]")]
public class FlightsimController : Controller
{
private readonly ILogger<FlightsimController> _logger;
public FlightsimController(ILogger<FlightsimController> logger)
{
_logger = logger;
}
public async Task<IActionResult> Index()
{
//Retrieve and Check current user status
UserModel user = HttpContext.Session.GetObject<UserModel>("User");
2022-02-18 22:01:53 +00:00
if(user == null){
TempData["Error"] = "You must be logged in before you are able to view the FlightSim Page";
return RedirectToAction("Index", "Home");
}
//Retrieve the user's latest sim position and construct it into FlightsimModel
2022-02-18 22:01:53 +00:00
if (user.Route == null){
TempData["Error"] = "You must have a route planned before you are able to view the Flightsim page";
return RedirectToAction("Index", "Route");
}
2022-02-18 21:13:21 +00:00
SimPositionModel latestPositionModel = await Mongo.GetLatestData(user.EMail);
RouteModel route = await RouteModel.StringToRoute(user.Departure, user.Arrival, user.Cruise, user.Route);
2022-02-18 21:13:21 +00:00
IWaypoint closest = DetermineClosest(route, latestPositionModel.LatestPosition);
return View(new FlightsimModel(latestPositionModel, closest));
}
private IWaypoint DetermineClosest(RouteModel route, SimPosition currentPosition){
IWaypoint closest = null;
float closestDistance = float.MaxValue;
//Assuming that we are on the earth for simplicity
IWaypoint waypoint = route.Departure;
while (waypoint.Next != null)
{
int earthRadius = 6371;
float distanceLat = DegreesToRadians(waypoint.Latitude - currentPosition.Latitude);
float distanceLon = DegreesToRadians(waypoint.Longitude - currentPosition.Longitude);
float latitude1 = DegreesToRadians(currentPosition.Latitude);
float latitude2 = DegreesToRadians(waypoint.Latitude);
var a = Math.Sin(distanceLat/2) * Math.Sin(distanceLat/2) + Math.Sin(distanceLon/2) * Math.Sin(distanceLon/2) * Math.Cos(latitude1) * Math.Cos(latitude2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));
2022-02-18 21:13:21 +00:00
float distance = (float)(earthRadius * c);
2022-02-18 21:13:21 +00:00
if (distance < closestDistance)
{
closest = waypoint;
closestDistance = distance;
}
waypoint = waypoint.Next;
}
return closest;
}
2022-02-18 21:13:21 +00:00
private float DegreesToRadians(float degrees){
return (float)(degrees * Math.PI / 180);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View("Error!");
}
}
}