function MatchEvent(event){
  var self = this;
  self.id = ko.observable(event.id);
  self.eventType = ko.observable(event.EventType);
  self.eventTimeStamp = ko.observable(event.TimeStamp);
  self.eventPoint = ko.observable(event.Points);
}
function Team (team){
  var self = this;
  self.name = ko.observable(team.name);
  self.points = ko.observable(team.points);
  self.eventHistory = ko.observableArray(team.EventHistory.map((evt) => new MatchEvent(evt)));
}

function ScoreboardViewModel() {
  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
  const matchDuration = 80 * 60 * 1000;

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

  this.gameOn = ko.observable(false);

  this.homeTeamName = ko.observable("Uckfield RFC");
  this.homeTeamColor = ko.observable("#ff0000");
  this.homeTeamPoints = ko.observable(0);
  this.homeTeamLogo = ko.observable("");
  this.homeTeamEvents = ko.observable([]);

  this.awayTeamName = ko.observable("Away team");
  this.awayTeamColor = ko.observable("#0000ff");
  this.awayTeamPoints = ko.observable(0);
  this.awayTeamLogo = ko.observable("");
  this.awayEvents = ko.observableArray([]);

  self.timerValue = ko.computed( function() {
    const currentTime = new Date();
    const elapsedTime = currentTime - self.kickOffTime();
    const remainingTime = Math.max(0, matchDuration - elapsedTime);
  
    const minutes = Math.floor(remainingTime / 60000);
    const seconds = Math.floor((remainingTime % 60000) / 1000);
    return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
  });

  self.halfIndicator = ko.computed(function(){
    const gameState = self.gameState();
    if(gameState ==="WaitingForStart"){
      var dt = self.kickOffTime();
      return `KO @${String(dt.getHours()).padStart(2,"0")}:${String(dt.getMinutes()).padStart(2,"0")}`;
    }
    if(gameState === "FirstHalf"){
      return "1st Half";
    }
    if(gameState === "SecondHalf"){
      return "2nd Half";
    }
  });

  var fetchNewData = function() {
    currentReq = fetch(apiUrl, {
      method: 'GET',
      headers: {
        'x-api-key': apiKey
      },
    });
    
    currentReq
      .then(processResponse)
      .then(processJson)
      .catch((error)=>console.log(`Error Occurred retrieving data ${error}`))
      .then(scheduleNewDataFetch);
  };

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

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

    self.homeTeamName(data.home.name);
    self.awayTeamName(data.away.name);
    
    self.homeTeamPoints(data.home.points);
    self.awayTeamPoints(data.away.points);
  };
  
  var scheduleNewDataFetch = function() {    
    if (timeout) {
      clearTimeout(timeout);  
    }
    timeout = setTimeout(fetchNewData, INTERVAL);
  };

  fetchNewData(); // Starts the update loop
}

ko.applyBindings(new ScoreboardViewModel());