package library

import (
	"app/shelfly/internal/models"
	"app/shelfly/query"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"gorm.io/gorm"
)

func ScanFolder(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		// Récupérer l'ID depuis les paramètres de l'URL
		id := mux.Vars(r)["id"]
		var existingPath models.PathDownload
		if err := db.First(&existingPath, "id = ?", id).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				http.Error(w, `{"error": "Path not found"}`, http.StatusNotFound)
				return
			}
			http.Error(w, `{"error": "Failed to retrieve path"}`, http.StatusInternalServerError)
			return
		}
		// fmt.Println(existingPath.Path)
		// info, _ := os.Stat(existingPath.Path)
		// fmt.Println(info)
		err := filepath.Walk(existingPath.Path, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				fmt.Println(err)
				return err
			}

			fmt.Printf("dir: %v: name: %s\n", info.IsDir(), path)
			if !info.IsDir() {
				//log.Fatalf("Lancement get info")

				fmt.Printf("%s", info.Name()+"\n")
				str := info.Name()
				str = cleanMovieName(str)
				str1 := strings.Replace(str, " ", "+", -1)
				url := "https://api.themoviedb.org/3/search/movie?query=" + str1 + "&language=fr"
				fmt.Println(string(url))
				req, _ := http.NewRequest("GET", url, nil)

				req.Header.Add("accept", "application/json")
				req.Header.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzM2VlNTBlOGJlNGQ4YjFkMTYwOTgyMjFhMmEyMjgxOSIsIm5iZiI6MTYwMDc1OTQzOS41NjksInN1YiI6IjVmNjlhNjhmYTZlMmQyMDAzODU5OTVlYiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.wJUlv5oiJhyB7uwb6mcYEnmKh_bh6vC0u0kBuz6ZsGk")

				res, _ := http.DefaultClient.Do(req)

				defer res.Body.Close()
				body, _ := io.ReadAll(res.Body)

				var result map[string]interface{}
				err = json.Unmarshal(body, &result)
				if err != nil {
					log.Fatalf("Erreur lors du décodage de la réponse JSON: %v", err)
				}

				// Afficher le contenu du résultat
				//fmt.Printf("Résultat brut : %+v\n", result)
				if results, ok := result["results"].([]interface{}); ok {
					for _, item := range results {
						if movie, ok := item.(map[string]interface{}); ok {
							fmt.Println(movie)
							// title := movie["title"]
							// releaseDate := movie["release_date"]
							// overview := movie["overview"]

							//fmt.Printf("Titre: %v, Date de sortie: %v, Résumé: %v\n", title, releaseDate, overview)
							break
						}
					}
				}
				log.Fatalf("Lancement api")

				section := models.LibrarySection{
					Name:        "Films",
					SectionType: 1,
					Language:    "fr",
					UUID:        "section-uuid-123",
					CreatedAt:   time.Now().String(),
					UpdatedAt:   time.Now().String(),
				}
				if err := db.Create(&section).Error; err != nil {
					log.Fatalf("Failed to insert LibrarySection: %v", err)
				}

				metadata := models.MetadataItem{
					LibrarySectionID: section.ID,
					MetadataType:     1,
					GUID:             "film-guid-123",
					Title:            "Inception",
					TitleSort:        "Inception",
					OriginalTitle:    "Inception",
					Studio:           "Warner Bros",
					Rating:           8.8,
					ContentRating:    "PG-13",
					Tagline:          "Your mind is the scene of the crime.",
					Summary:          "A skilled thief is offered a chance to erase his criminal past.",
					Index:            1,
					Duration:         8880,
					ReleaseDate:      time.Date(2010, 7, 16, 0, 0, 0, 0, time.UTC).String(),
					CreatedAt:        time.Now().String(),
					UpdatedAt:        time.Now().String(),
				}
				if err := db.Create(&metadata).Error; err != nil {
					log.Fatalf("Failed to insert MetadataItem: %v", err)
				}

				mediaItem := models.MediaItem{
					MetadataItemID: metadata.ID,
					Duration:       8880,
					Bitrate:        3000,
					Width:          1920,
					Height:         1080,
					AspectRatio:    16.0 / 9.0,
					AudioCodec:     "AAC",
					VideoCodec:     "H264",
					Container:      "MP4",
					CreatedAt:      time.Now().String(),
					UpdatedAt:      time.Now().String(),
				}
				if err := db.Create(&mediaItem).Error; err != nil {
					log.Fatalf("Failed to insert MediaItem: %v", err)
				}

				mediaPart := models.MediaPart{
					MediaItemID: mediaItem.ID,
					File:        "/path/to/inception.mp4",
					Duration:    8880,
					Size:        1500000000,
					Indexes:     "1",
					CreatedAt:   time.Now().String(),
					UpdatedAt:   time.Now().String(),
				}
				if err := db.Create(&mediaPart).Error; err != nil {
					log.Fatalf("Failed to insert MediaPart: %v", err)
				}
				fmt.Println("Film inserted successfully!")

			}
			// api

			return nil
		})
		if err != nil {
			fmt.Println(err)
		}
	}
}
func cleanMovieName(filename string) string {
	// Étape 1: Supprimer l'extension du fichier
	extPattern := regexp.MustCompile(`\.[^.]+$`)
	filename = extPattern.ReplaceAllString(filename, "")

	// Étape 2: Remplacer les points par des espaces
	filename = strings.ReplaceAll(filename, ".", " ")

	// Étape 3: Supprimer les informations techniques
	infoPattern := regexp.MustCompile(`(?i)(\b19[0-9]{2}\b|\b20[0-9]{2}\b|multi|truefrench|french|1080p|720p|4k|bluray|hdlight|x265|x264|h264|wawacity|blue|mkv|avi|mp4|m4v|Vff|WEBRIP|ING|-)`)
	filename = infoPattern.ReplaceAllString(filename, "")

	// Étape 4: Nettoyer les espaces supplémentaires
	filename = strings.TrimSpace(filename)
	filename = regexp.MustCompile(`\s+`).ReplaceAllString(filename, " ")

	return filename
}
func CreateDefaultFolder(db *gorm.DB) {
	folders := []string{"Film", "Série", "Manga"}

	for _, name := range folders {
		path := "upload/" + name

		if _, err := os.Stat(path); os.IsNotExist(err) {
			err := os.MkdirAll(path, 0755) // MkdirAll au cas où des dossiers parents manquent
			if err != nil {
				fmt.Printf("Erreur lors de la création du dossier %s : %v\n", path, err)
			} else {
				pathDownload := models.PathDownload{
					Path:     path,
					PathName: name,
				}
				q := query.Use(db)
				if err := q.PathDownload.Create(&pathDownload); err != nil {
					fmt.Printf(`{"error": "Failed to create path"}`, http.StatusInternalServerError)
					return
				}
				fmt.Printf("Dossier créé : %s\n", path)
			}
		} else {
			fmt.Printf("Dossier déjà existant : %s\n", path)
		}
	}
}
