@model NzbDrone.Web.Models.UpdateModel
@{ViewBag.Title = "Update";}

@if (Model.UpdatePackage == null)
{
    <h2>
        There are no updates available.</h2>
}
else
{
    <h2>
        Available Update: @Model.UpdatePackage.Version
        @Ajax.ActionLink("Update", "StartUpdate", "Update", new AjaxOptions{ OnSuccess = "updateStarted" })
        @Html.HiddenFor(m => m.UpdatePackage.Version)
    </h2> 
}
@if (Model.LogFiles.Count != 0)
{
    <h3>
        Update Logs (@Model.LogFolder)
    </h3>
    <br />
    foreach (var log in Model.LogFiles)
    {
    <div>
        <a href="@Url.Action("ViewLog", "Update", new { filePath = log.Value })">
            @log.Key.ToString("MMM dd, hh:mm tt")</a>
    </div>
    }
}

@section Scripts
{
    <script type="text/javascript">
        function updateStarted() {
            var expectedVersion = $('#UpdatePackage_Version').val();
            var errors = 0;

            //Pool the server every 5 seconds for a change in state
            $.doTimeout('updateStarted', 5000, function () {
                $.ajax({
                    url: '/Health/Index',
                    type: "GET",
                    error: function (jqXHR, textStatus, errorThrown) {
                        //Handle the first error that occured
                        errors++;
                    },
                    success: function (data, textStatus, jqXHR) {
                        if (errors > 0) {
                            //Kill the timer, redirect
                            $.doTimeout('updateStarted');
                            window.location = '/Update/Post?expectedVersion=' + expectedVersion;
                        }
                    }
                });

                return true;
            });
        }
    </script>
}