@page
@using Microsoft.AspNetCore.Http
@using JtkMainServer.Managers
@{
    Layout = null;

    // 경위도 사이의 거리 구하기
    double Distance(double lat1, double lon1, double lat2, double lon2) {
        double theta = lon1 - lon2;
        double dist = Math.Sin(DegreeToRadian(lat1)) * Math.Sin(DegreeToRadian(lat2)) + Math.Cos(DegreeToRadian(lat1)) * Math.Cos(DegreeToRadian(lat2)) * Math.Cos(DegreeToRadian(theta));

        dist = Math.Acos(dist);
        dist = RadianToDegree(dist);
        dist *= 111189.57696;

        return dist;
    }

    // This function converts decimal degrees to radians
    double DegreeToRadian(double deg) => deg * Math.PI / 180.0;

    // This function converts radians to decimal degrees
    double RadianToDegree(double rad) => rad * 180 / Math.PI;



    var longitude = 0.0;
    if (HttpContext.Request.Query.TryGetValue("longitude", out var longitudeList)) {
        longitude = double.Parse(longitudeList[0]);
    }

    var latitude = 0.0;
    if (HttpContext.Request.Query.TryGetValue("latitude", out var latitudeList)) {
        latitude = double.Parse(latitudeList[0]);
    }

    var includeDistance = longitude != 0.0 && latitude != 0.0;
}
@if (includeDistance) {
    var places = PlaceManager.GetAllPlaces();
    var ordered = places.OrderBy(place => {
        var split = place.location.Split(',');
        var lat = double.Parse(split[0]);
        var lng = double.Parse(split[1]);
        return Distance(lat, lng, latitude, longitude);
    }).Select(place => {
        var split = place.location.Split(',');
        var lat = double.Parse(split[0]);
        var lng = double.Parse(split[1]);
        return (place.name, place.id, place.remainingPcCount, place.totalPcCount, distance: Distance(lat, lng, latitude, longitude));
    });
    <table class="table">
        <thead>
            <tr>
                <th>
                    PC방 이름
                </th>
                <th>
                    좌석 여유
                </th>
                <th>
                    거리
                </th>
                <th>
                    최근 평가
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in ordered) {
            <tr>
                <td><a href="@($"/PCBang/Details?id={item.Item2}")">@item.Item1</a></td>
                @{var percentage = (float)item.Item3 / (float)item.Item4;}
                @if (item.Item4 < 0) {
                    <td>알 수 없음</td>
                } else {
                    @if (percentage > 0.5) {
                        <td><span style="color:forestgreen">@item.Item3</span> / @item.Item4</td>
                    } else if (percentage > 0.2) {
                        <td><span style="color:darkorange">@item.Item3</span> / @item.Item4</td>
                    } else {
                        <td><span style="color:orangered">@item.Item3</span> / @item.Item4</td>
                    }
                }
                @{
                    var dist = item.Item5;
                    var distColor = "forestgreen";
                    if (dist > 10000) {
                        distColor = "orangered";
                    } else if (dist > 3000) {
                        distColor = "darkorange";
                    }

                    var reviews = DbManager.GetPlaceReviews(item.Item2);
                    var recentAverage = reviews.Length > 0 ? reviews.Take(30).Average(review => review.score) : 0d;

                    var reviewStr = reviews.Length > 0 ? "좋음" : "평가 부족";
                    var reviewColor = reviews.Length > 0 ? "forestgreen" : "black";
                    var reviewStars = reviews.Length > 0 ? 5 : -1;
                    if (reviews.Length > 0) {
                        if (recentAverage < -0.667) {
                            reviewStr = "나쁨";
                            reviewColor = "darkred";
                            reviewStars = 1;
                        } else if (recentAverage < -0.333) {
                            reviewStr = "대체로 나쁨";
                            reviewColor = "darkorange";
                            reviewStars = 2;
                        } else if (recentAverage < 0.333) {
                            reviewStr = "복합적";
                            reviewColor = "chocolate";
                            reviewStars = 3;
                        } else if (recentAverage < 0.667) {
                            reviewStr = "대체로 좋음";
                            reviewColor = "darkolivegreen";
                            reviewStars = 4;
                        }
                    }
                }
                <td>@(Html.Raw($"<span style=\"color:{distColor}\">" + (dist >= 1000 ? $"{dist / 1000.0:N1}km" : $"{dist:N0}m") + "</span>"))</td>
                @*<td>@(Html.Raw($"<span style=\"color:{reviewColor}\">{reviewStr}</span>"))</td>*@
                <td style="color:@reviewColor">
                    @if (reviewStars == -1) {
                        @reviewStr
                    } else {
                        @foreach (int i in Enumerable.Range(0, reviewStars)) {
                            <span class="glyphicon glyphicon-star"></span>
                        }
                        @foreach (int i in Enumerable.Range(0, 5 - reviewStars)) {
                            <span class="glyphicon glyphicon-star-empty"></span>
                        }
                    }

                </td>
            </tr>
            }
        </tbody>
    </table>
} else {
    <table class="table">
        <thead>
            <tr>
                <th>
                    PC방
                </th>
                <th>
                    여유
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in PlaceManager.GetAllPlaces()) {
                <tr>
                    <td><a href="@($"/PCBang/Details?id={item.id}")">@item.name</a></td>
                    @{var percentage = (float)item.remainingPcCount / (float)item.totalPcCount;}
                    @if (item.totalPcCount < 0) {
                        <td>알 수 없음</td>
                    } else {
                        @if (percentage > 0.5) {
                            <td><span style="color:forestgreen">@item.remainingPcCount</span> / @item.totalPcCount</td>
                        } else if (percentage > 0.2) {
                            <td><span style="color:darkorange">@item.remainingPcCount</span> / @item.totalPcCount</td>
                        } else {
                            <td><span style="color:orangered">@item.remainingPcCount</span> / @item.totalPcCount</td>
                        }
                    }
                </tr>
            }
        </tbody>
    </table>
}