package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/zmb3/spotify"
)

var oauthToken string

func StartAuthorizationCodeFlow() (authClient *spotify.Client) {
    // first start an HTTP server
    http.HandleFunc("/callback", completeAuth)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // log.Println("Got request for:", r.URL.String())
    })
    go http.ListenAndServe(":8080", nil)

    url := auth.AuthURL(state)
    fmt.Println("Please log in to Spotify by visiting the following page in your browser:\n", url)
   
    client := <-ch

    oauthToken = extractToken(client)

    // use the client to make calls that require authorization
    user, spotify_auth_err := client.CurrentUser()
    if spotify_auth_err != nil {
        log.Fatal(spotify_auth_err)
    }
    fmt.Println("You are logged in as:", user.ID)
    return client
}

func completeAuth(w http.ResponseWriter, r *http.Request) {
    tok, err := auth.Token(state, r)
    if err != nil {
        http.Error(w, "Couldn't get token", http.StatusForbidden)
        log.Fatal(err)
    }
    if st := r.FormValue("state"); st != state {
        http.NotFound(w, r)
        log.Fatalf("State mismatch: %s != %s\n", st, state)
    }
    // use the token to get an authenticated client
    client := auth.NewClient(tok)
    status = 2

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprint(w, "test <script>window.close()</script>")
    ch <- &client
}

func extractToken(client *spotify.Client) (tokenString string) {
    token, err := client.Token()
    if err != nil {
        log.Fatal(err)
    }
    return token.AccessToken
}
