package renders

import (
	"app/shelfly/internal/models"
	"encoding/json"
	"net/http"
	"text/template"

	"gorm.io/gorm"
)


func Login(w http.ResponseWriter, r *http.Request){
	renderTemplate(w,"login",nil)
}
func Dashboard(db *gorm.DB)http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
    var paths []models.PathDownload
    if err := db.Find(&paths).Error; err != nil {
        http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError)
        return
    }
    data := map[string]interface{}{
        "paths": paths,
    }
    
	renderTemplate(w,"dashboard",data)
}

}
func MenuLibrary(db *gorm.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        var currentPaths []models.PathDownload
        if err := db.Find(&currentPaths).Error; err != nil {
            http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError)
            return
        }

        // Récupérer l'ancienne version des paths (si existante)
        lastUpdate := r.Header.Get("HX-Current-Paths")
        var previousPaths []models.PathDownload
        if lastUpdate != "" {
            json.Unmarshal([]byte(lastUpdate), &previousPaths)
        }

        // Convertir en JSON pour comparaison
        currentJSON, _ := json.Marshal(currentPaths)
        previousJSON, _ := json.Marshal(previousPaths)

        // Vérifier si les paths ont changé
        pathsChanged := string(currentJSON) != string(previousJSON)

        data := map[string]interface{}{
            "paths": currentPaths,
        }

        // Si HTMX request, ajouter les headers appropriés
        if r.Header.Get("HX-Request") == "true" {
            if pathsChanged {
                w.Header().Set("HX-Trigger", "pathsUpdated")
            }
            w.Header().Set("HX-Current-Paths", string(currentJSON))
        }

        renderPartial(w, "dashboard", data)
    }

}
func Settings(w http.ResponseWriter, r *http.Request) {
    data := map[string]interface{}{
        "Title": "Settings Page",
        "Options": []string{"Option 1", "Option 2", "Option 3"},
    }
    renderPartial(w, "settings", data)
}


func Library(w http.ResponseWriter, r *http.Request) {
    renderPartial(w, "library",nil)
}

func GoDownload(w http.ResponseWriter, r *http.Request) {
    renderPartial(w, "godownloader_download",nil)
}
func GoDownloadLinkCollectors(w http.ResponseWriter, r *http.Request) {
    renderPartial(w, "godownloader_linkcollectors",nil)
}
func GoDownloadSetting(w http.ResponseWriter, r *http.Request) {
    renderPartial(w, "godownloader_setting",nil)
}


func renderTemplate(w http.ResponseWriter, templ string, data map[string]interface{}) {
    t, err := template.ParseFiles(
        "./templates/head.pages.tmpl",      // Template inclus
        "./templates/" + templ + ".pages.tmpl", // Template principal
    )

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // Exécutez explicitement le template principal
    err = t.ExecuteTemplate(w, templ+".pages.tmpl", data)

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func renderPartial(w http.ResponseWriter, templ string, data map[string]interface{}) {
    t, err := template.ParseFiles("./templates/" + templ + ".pages.tmpl")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    err = t.Execute(w, data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

