package main

import (
    // "os"
    "fmt"
    "net/http"
    "html/template"
    "regexp"
    "io/ioutil"
    "encoding/json"
)

var templates = template.Must(template.ParseGlob("pages/*.html"))
var validPath = regexp.MustCompile("^/(webclient)/(.*)$")

type Page struct {
    Title string
    Body  []byte
}

// func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
//     fmt.Println("Running makeHandler")
//     return func(w http.ResponseWriter, r *http.Request) {
//         m := validPath.FindStringSubmatch(r.URL.Path)
//         if m == nil {
//             http.NotFound(w, r)
//             return
//         }
//         fmt.Println("makeHandler::request::" + r.RequestURI)
//         fn(w, r, m[2])
//     }
// }

type testStructForWeb struct {
    ID string
    Name string
    Owner string
}

type Context struct { 
    Items []testStructForWeb
}

func serveSingle(pattern string, filename string) {
    http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, filename)
    })
}

func webclientHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("webclientHandler called")

    var result []testStructForWeb

    url := baseURL_playlists + "?limit=50&offset=0"

    httpClient := &http.Client{}
    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("Authorization", "Bearer "+oauthToken)
    res, _ := httpClient.Do(req)

    body, _ := ioutil.ReadAll(res.Body)
    data := new(spotifyPlaylistsOfUser)
    json.Unmarshal(body, &data)
    var counter = 0

    for _,playlist := range data.Items {
        counter++
        result = append(result, testStructForWeb{ID: playlist.ID, Name: playlist.Name, Owner: (playlist.Owner.ID)})
    }
    if data.Total > 50 {
        for(data.Next != nil) {
            nextUrl := *data.Next
            request, _ := http.NewRequest("GET",nextUrl, nil)
            request.Header.Set("Authorization", "Bearer "+oauthToken)
            response, _ := httpClient.Do(request)

            body, _ = ioutil.ReadAll(response.Body)
            json.Unmarshal(body, &data)
            for _,playlist := range data.Items {
                counter++ 
                result = append(result, testStructForWeb{ID: playlist.ID, Name: playlist.Name, Owner: playlist.Owner.ID})
            }
        }
    }

    
    playlists := Context{Items: result}

    templates.ExecuteTemplate(w, "playlists", playlists)
}

func submitDownloadQueueHandler(w http.ResponseWriter, r *http.Request) {
    // for playlist_id in all_playlists
        // if r.PostFormValue(playlist_id)
    // end for
}

func startWebServer() {
    http.HandleFunc("/webclient/", webclientHandler)
    http.HandleFunc("/submitDownloadQueue/", submitDownloadQueueHandler)

    serveSingle("/static/tables.css", "./static/tables.css")

    fmt.Println("http://localhost:8088/webclient")
    http.ListenAndServe("localhost:8088", nil)
}
