package handlers

import (
	"encoding/json"
	"log"
	"net/http"
	"reader/internal/processor"
)

type VideoRequest struct {
	Date      string `json:"date"`
	StartTime string `json:"start_time"`
	EndTime   string `json:"end_time"`
}

// Download processes Download request.
func Download(w http.ResponseWriter, r *http.Request) {
	log.Printf("new download request: %+v\n", r)

	downloadRequest := VideoRequest{}

	err := json.NewDecoder(r.Body).Decode(&downloadRequest)
	if err != nil {
		log.Printf("json decode error: %v\n", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	pathFileNameRes, err := processor.Process(downloadRequest.Date, downloadRequest.StartTime, downloadRequest.EndTime)
	if err != nil {
		log.Printf("process error: %v\n", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "video/mp4")
	// Разрешаем частичную загрузку (поддержка перемотки)
	w.Header().Set("Accept-Ranges", "bytes")

	http.ServeFile(w, r, pathFileNameRes)
}

// HLS processes Download request.
func HLS(w http.ResponseWriter, r *http.Request) {
	log.Printf("new hls request: %+v\n", r)

	path := "/home/psa/GoRepository/data/1280x720/"

	w.Header().Set("Access-Control-Allow-Origin", "*")
	http.StripPrefix("/hls", http.FileServer(http.Dir(path))).ServeHTTP(w, r)
}
