package api

import (
    "encoding/json"
    "fmt"
    "net/http"

    "arimelody-web/controller"
    "arimelody-web/log"
    "arimelody-web/model"
)

type (
    Track struct {
        *model.Track
        Releases    []string    `json:"releases"`
    }
)

func ServeAllTracks(app *model.AppState) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        type Track struct {
            ID      string  `json:"id"`
            Title   string  `json:"title"`
        }
        var tracks = []Track{}

        var dbTracks = []*model.Track{}
        dbTracks, err := controller.GetAllTracks(app.DB)
        if err != nil {
            fmt.Printf("WARN: Failed to pull tracks from DB: %s\n", err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }

        for _, track := range dbTracks {
            tracks = append(tracks, Track{
                ID: track.ID,
                Title: track.Title,
            })
        }

        w.Header().Add("Content-Type", "application/json")
        encoder := json.NewEncoder(w)
        encoder.SetIndent("", "\t")
        err = encoder.Encode(tracks)
        if err != nil {
            fmt.Printf("WARN: Failed to serve all tracks: %s\n", err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
    })
}

func ServeTrack(app *model.AppState, track *model.Track) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        dbReleases, err := controller.GetTrackReleases(app.DB, track.ID, false)
        if err != nil {
            fmt.Printf("WARN: Failed to pull track releases for %s from DB: %s\n", track.ID, err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
        
        releases := []string{}
        for _, release := range dbReleases {
            releases = append(releases, release.ID)
        }

        w.Header().Add("Content-Type", "application/json")
        encoder := json.NewEncoder(w)
        encoder.SetIndent("", "\t")
        err = encoder.Encode(Track{ track, releases })
        if err != nil {
            fmt.Printf("WARN: Failed to serve track %s: %s\n", track.ID, err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
    })
}

func CreateTrack(app *model.AppState) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        session := r.Context().Value("session").(*model.Session)

        var track model.Track
        err := json.NewDecoder(r.Body).Decode(&track)
        if err != nil {
            http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
            return
        }

        if track.Title == "" {
            http.Error(w, "Track title cannot be empty\n", http.StatusBadRequest)
            return
        }

        id, err := controller.CreateTrack(app.DB, &track)
        if err != nil {
            fmt.Printf("WARN: Failed to create track: %s\n", err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
            return
        }

        app.Log.Info(log.TYPE_MUSIC, "Track \"%s\" (%s) created by \"%s\".", track.Title, track.ID, session.Account.Username)

        w.Header().Add("Content-Type", "text/plain")
        w.WriteHeader(http.StatusCreated)
        w.Write([]byte(id))
    })
}

func UpdateTrack(app *model.AppState, track *model.Track) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "/" {
            http.NotFound(w, r)
            return
        }

        session := r.Context().Value("session").(*model.Session)

        err := json.NewDecoder(r.Body).Decode(&track)
        if err != nil {
            http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
            return
        }

        if track.Title == "" {
            http.Error(w, "Track title cannot be empty\n", http.StatusBadRequest)
            return
        }

        err = controller.UpdateTrack(app.DB, track)
        if err != nil {
            fmt.Printf("WARN: Failed to update track %s: %s\n", track.ID, err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
            return
        }

        app.Log.Info(log.TYPE_MUSIC, "Track \"%s\" (%s) updated by \"%s\".", track.Title, track.ID, session.Account.Username)

        w.Header().Add("Content-Type", "application/json")
        encoder := json.NewEncoder(w)
        encoder.SetIndent("", "\t")
        err = encoder.Encode(track)
        if err != nil {
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
    })
}

func DeleteTrack(app *model.AppState, track *model.Track) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "/" {
            http.NotFound(w, r)
            return
        }

        session := r.Context().Value("session").(*model.Session)

        var trackID = r.URL.Path[1:]
        err := controller.DeleteTrack(app.DB, trackID)
        if err != nil {
            fmt.Printf("WARN: Failed to delete track %s: %s\n", trackID, err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }

        app.Log.Info(log.TYPE_MUSIC, "Track \"%s\" (%s) deleted by \"%s\".", track.Title, track.ID, session.Account.Username)
    })
}
