package main

import (
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/go-ini/ini"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

var config MainConfig

type MainConfig struct {
	Listenaddr string   //监听地址
	Baseurl    string   //监听地址
	Rootdir    string   //root文件夹
	DvrDir     []string //dvr文件夹
	Secure     string   //加密字符串
}

func (o *MainConfig) ReadConfig() bool {
	dir, _ := os.Getwd() //filepath.Abs(filepath.Dir(os.Args[0]))
	path := dir + string(filepath.Separator)
	var ret = false
	fini, err := ini.Load(path + "main.ini")
	if err == nil {
		fsec := fini.Section("mediasvr")
		if fsec != nil {
			o.Listenaddr = fsec.Key("listenaddr").String()
			o.Baseurl = fsec.Key("baseurl").String()
			o.Secure = fsec.Key("secure").String()
			o.Rootdir = fsec.Key("rootdir").String()
			dvrdir := fsec.Key("dvrdir").String()
			if len(dvrdir) > 0 {
				o.DvrDir = strings.Split(dvrdir, ",")
			}
			ret = true
		}
	}
	return ret
}

// 根据流ID和日期，获取对应的回放文件链接
func getFile(streams, date string) []string {
	var fileList []string
	for _, dir := range config.DvrDir {
		path := string(filepath.Separator) + dir + string(filepath.Separator) + streams + string(filepath.Separator) + date
		if rd, err := ioutil.ReadDir(config.Rootdir + path); err == nil {
			for _, fi := range rd {
				//过滤掉路径和非mp4文件
				if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".mp4") {
					httpurl := config.Baseurl + strings.ReplaceAll(path+string(filepath.Separator)+fi.Name(), string(filepath.Separator), "/")
					fileList = append(fileList, httpurl)
				}
			}
		}
	}
	sort.Strings(fileList)
	return fileList
}

func SearchFile(c echo.Context) error {
	streamid := c.Param("streamid")
	date := c.Param("date")
	debug := c.Param("debug")
	var list []string
	//hxz
	if len(streamid) > 0 && len(date) > 0 {
		list = getFile(streamid, date)
	}
	if len(list) == 0 {
		list = make([]string, 0)
	}
	if debug == "bug" {
		return c.JSON(http.StatusOK, list)
	} else if buf, err := json.Marshal(list); err == nil {
		enstr := "LC" + base64.StdEncoding.EncodeToString(buf)
		//hxz
		return c.String(http.StatusOK, enstr)
	}
	return nil
}

func main() {
	if !config.ReadConfig() {
		return
	}
	e := echo.New()
	e.Use(middleware.Recover())
	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin"},
	}))

	e.Debug = true
	e.HideBanner = true

	//注册一个Get请求, 路由地址为: 并且绑定一个控制器函数, 这里使用的是闭包函数。
	e.GET("/list/:streamid/:date", SearchFile)
	e.GET("/list/:streamid/:date/:debug", SearchFile)
	e.Static("/", config.Rootdir)

	//e.StartTLS(config.Listenaddr, "server.crt", "server.key")
	e.Logger.Fatal(e.Start(config.Listenaddr))
}
