
function viewModel() {
    const apiKey = '396A62D6-0192-4738-8F45-8AAF7BCFA3EC'; // Replace with your actual API key
    const apiUrl = 'https://localhost:7005/api/Score'; // Replace with your API endpoint URL

    var self = this;

    //API poll variables
    var INTERVAL = 5000;
    var timeout = null;
    var currentReq = null;
    //knockout variables
    self.gameState = ko.observable("");
    self.kickOffTime = ko.observable(new Date());

    self.homeTeamName = ko.observable("Uckfield RFC");
    self.homeTeamColor = ko.observable("#ff0000");
    self.awayTeamName = ko.observable("Away team");
    self.awayTeamColor = ko.observable("#0000ff");

    self.eventsHome = ko.observableArray([]);
    self.eventsAway = ko.observableArray([]);

    this.homeTeamColor = ko.observable("#ff0000");
    this.awayTeamColor = ko.observable("#0000ff");

    self.eventList = ko.observableArray([]);

    var fetchNewData = function () {
        currentReq = fetch(apiUrl, {
            method: 'GET',
            headers: {
                'x-api-key': apiKey
            },
        });

        currentReq
            .then(processResponse)
            .then(processJson)
            .catch((error) => {
                return console.log(`Error Occurred retrieving data ${error}`);
            })
            .then(scheduleNewDataFetch);
    };

    var processResponse = function (response) {
        if (!response.ok) {
            INTERVAL = 60000;
            throw new Error('Network response was not ok');
        }
        if (response.status === 204) {
            INTERVAL = 60000;
            return Promise.reject('No Game');
        }
        INTERVAL = 5000;
        return response.json();
    };

    var processJson = function (data) {
        self.gameState(data.state);
        self.kickOffTime(new Date(data.startedAt));

        self.homeTeamName(data.home.name);
        self.awayTeamName(data.away.name);

        self.homeTeamColor(data.home.color);
        self.awayTeamColor(data.away.color);

        self.eventList(data.eventHistory);
    };

    var scheduleNewDataFetch = function () {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(fetchNewData, INTERVAL);
    };

    self.getEventMessage = function(evt) {
        var eventDate = new Date(evt.eventDate);
        var timeElapsed = eventDate - self.kickOffTime();
        var diffMins = Math.round(((timeElapsed % 86400000) % 3600000) / 60000);
        return `T${diffMins}: ${evt.eventType} Scored`
    }

    self.getScoreAtEvent = function(evtId){
        var evts = self.eventList();
        var homeScore = 0;
        var awayScore = 0;
        evts.forEach(evt => {
            if(evt.id <= evtId){
                if(evt.category ==='Home'){
                    homeScore += evt.points;
                } else {
                    awayScore += evt.points;
                }
            }
        });
        return `${homeScore} - ${awayScore}`;
    }

    fetchNewData(); // Starts the update loop
};

ko.applyBindings(new viewModel());