package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

type Location struct {
	Country   string `json:"country"`
	Latitude  string `json:"lat"`
	Locatlity string `json:"locality"`
	Longitude string `json:"long"`
}

type Circuit struct {
	CircuitID string              `json:"circuitID"`
	URL       string              `json:"url"`
	Name      string              `json:"circuitName"`
	Location  map[string]Location `json:"Location"`
}

type Race struct {
	Season   string             `json:"season"`
	Round    string             `json:"round"`
	RaceName string             `json:"raceName"`
	Circuit  map[string]Circuit `json:"Circuit"`
	Date     time.Time          `json:"date"`
	Time     time.Time          `json:"time"`
	ULR      string             `json:"url"`
}

type Races struct {
	Races  map[string]Race `json:"Race"`
	Season string          `json:"season"`
}

type RaceTable struct {
	RaceTable map[string]Races `json:"Races"`
}

type MRData struct {
	MRData map[string]RaceTable `json:"RaceTable"`
}

// GetDataFromErgast download the data from the API.
func GetDataFromErgast() {
	resp, err := http.Get("http://ergast.com/api/f1/2019.json")
	if err != nil {
		panic(err.Error())
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err.Error())
	}
	defer resp.Body.Close()

	var jsonData map[string]MRData
	// var jsonData map[string]RaceTable
	err = json.Unmarshal([]byte(body), &jsonData)
	if err != nil {
		panic(err.Error())
	}

	for races := range jsonData {
		fmt.Println(races)
	}
}
