package api

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	ffmpeg "github.com/u2takey/ffmpeg-go"
)

func Test(r *GinRouter) {
	r.GET("/test/ffmpeg/cmd", FfmpegCmd)

}

func FfmpegCmd(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	split := ffmpeg.Input("./asset/00_00.png").Crop(800, 500, 500, 500).Output("./asset/500_500.png").OverWriteOutput()
	split.ErrorToStdOut().Run()
	return split, nil
}

func Printr(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	return len("61c3d4a0d6649a1d7353e2d9"), nil
}

func cropImage(x, y, w, h int32, xIndex, yIndex int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(50000)*time.Millisecond)
	cmd := exec.CommandContext(ctx, ffmpegExe,
		"-i", "./00_00.png",
		"-vf", fmt.Sprintf("crop=%d:%d:%d:%d", w, h, x, y),
		fmt.Sprintf("./12/%d_%d.png", xIndex, yIndex),
	)
	defer cancel()

	err := cmd.Run()
	if err != nil {
		fmt.Println("crop err", err)
	}
}

func scaleImage(x, y, w, h int32, xIndex, yIndex int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(50000)*time.Millisecond)
	// ffmpeg -i image_source -vf scale=width:height out_source
	cmd := exec.CommandContext(ctx, ffmpegExe,
		"-i", "./00_00.png",
		"-vf", fmt.Sprintf("scale=%d:%d", w, h),
		fmt.Sprintf("./12/%d_%d.png", xIndex, yIndex),
	)
	defer cancel()

	err := cmd.Run()
	if err != nil {
		fmt.Println("crop err", err)
	}
}

var ffmpegExe = ""

func HandleImage(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	fmt.Println("dir:", dir)
	var ffmpegExe string = dir + "/ffmpeg"
	split := ffmpeg.Input("./asset/00_00.png").Crop(800, 500, 500, 500).Output("./asset/500_500.png").OverWriteOutput()
	split.ErrorToStdOut().Run()
	return split, nil
}

func createLevel() {
	w := 1944
	h := 2592
	xIndex := 0
	yIndex := 0

	step := 510

	for {

		offsetX := xIndex * step
		cropX := offsetX - 1
		cropW := 512
		if xIndex == 0 {
			cropW = 511
			cropX = 0
		}
		isOver := false
		if (offsetX - 1 + cropW) >= w {
			cropW = w - offsetX + 1
			isOver = true
		}

		for {

			offsetY := yIndex * step
			cropY := offsetY - 1
			cropH := 512
			if yIndex == 0 {
				cropH = 511
				cropY = 0
			}
			isYOver := false
			if (offsetY - 1 + cropH) >= h {
				cropH = h - offsetY + 1
				isYOver = true
			}

			//开始按参数裁剪
			cropImage(int32(cropX), int32(cropY), int32(cropW), int32(cropH), xIndex, yIndex)
			fmt.Println("x:", cropX)
			fmt.Println("y:", cropY)
			fmt.Println("w:", cropW)
			fmt.Println("h:", cropH)
			fmt.Println("yIndex:", yIndex)

			yIndex = yIndex + 1

			if isYOver {
				break
			}
		}

		yIndex = 0
		xIndex = xIndex + 1
		if isOver {
			break
		}
	}
}
