package main

import (
	"fmt"
	"git.adphi.net/Adphi/ytsflix/handler"
	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"strings"
)

func main() {
	var storagePath = "/tmp"
	if os.Getenv("DATA_DIR") != "" {
		storagePath = os.Getenv("DATA_DIR")
	}
	logrus.Infof("Using directory: %s", storagePath)
	setupLogging()
	h, err := handler.NewHandler(storagePath)
	if err != nil {
		logrus.Fatal(err)
	}
	defer h.Close()

	r := mux.NewRouter()
	r.HandleFunc("/", h.Home).Methods(http.MethodGet)
	r.HandleFunc("/movies/{search}", h.Search).Methods(http.MethodGet)
	r.HandleFunc("/movie/{id}", h.Movie).Methods(http.MethodGet)
	r.HandleFunc("/torrent/{id}", h.Torrents).Methods(http.MethodGet)
	r.HandleFunc("/watch/{movie}", h.Serve).Methods(http.MethodGet)
	r.HandleFunc("/subs/{movie}/{sub}", h.Sub).Methods(http.MethodGet)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", 8080), r); err != nil {
		logrus.Fatal(err)
	}
}

func setupLogging() {
	level := os.Getenv("LOG_LEVEL")
	l := logrus.ErrorLevel
	for _, ll := range logrus.AllLevels {
		if strings.ToLower(level) == ll.String() {
			l = ll
			break
		}
	}
	logrus.SetLevel(l)
	logrus.Infof("Setting LOG_LEVEL: %s", l)
}
