﻿/// <reference path="~/scripts/jquery.min.js">

var bowlingUrl = "https://api.tenpin.co.uk/bowling/centres/";
//var bowlingUrl = "http://localhost:58269/TenPinAPIHost/bowling/centres/";
//var bowlingUrl = "http://apistaging.tenpin.co.uk/bowling/centres/";
var xhr = null;

function tenpinCallback() { }

function ApiProxy(apiUrl) 
{
    var _self = this;
    this._apiUrl = apiUrl;

    this.invoke = function (centre, method, data, callback) {

        var url = _self._apiUrl + centre + "/" + method;

        if (typeof (data.date) != "undefined") {
            var dateArr = data.date.split("/");
            url = url + "/" + dateArr.reverse().join("-");
        }

        if (typeof (data.time) != "undefined") {
            url = url + "/" + data.time.replace(":", "-");
        }
        
        delete data.time;
        delete data.date;

        xhr = $.ajax({
            url: url,
            type: "GET",
            data: data,
            cache: false,
            dataType: "jsonp",
            jsonpCallback: "tenpinCallback",
            success: function (r) {
                xhr = null;

                if (!callback) return;

                callback(r);
            },
            error: function (e) {
                window.location = "/bookings/error/";
            }
        });
    }
}

function ApiClient(apiUrl) 
{
    var _self = this;
    this._proxy = new ApiProxy(apiUrl);

    this.getOpeningHours = function (centre, from, to, callback) {
        _self._proxy.invoke(centre, "opening-hours", { from: from, to: to }, callback);
    }

    this.isCentreOnline = function (centre, callback) {
        _self._proxy.invoke(centre, "online", {}, callback);
    }

    this.availability = function (centre, date, time, players, games, callback) {
        _self._proxy.invoke(centre, "availability", { date: date, time: time, players: players, games: games }, callback);
    }

    this.scenarios = function (centre, date, time, players, games, callback) {
        _self._proxy.invoke(centre, "scenarios", { date: date, time: time, players: players, games: games }, callback);
    }
}

var tenpinApiClient = new ApiClient(bowlingUrl);

function Kill() {
    if (xhr) {
        xhr.abort();
    }
}


