package rrc

import (
	"math"

	"github.com/mjibson/go-dsp/fft"
	log "github.com/sirupsen/logrus"
	"gocv.io/x/gocv"
)

// FIXME: still need to implement the HFNoiseFilterFFT function

func HFNoiseFilterFFT(input gocv.Mat, radius int) gocv.Mat {
	// 将灰度图像转换为浮点数数组
	height := input.Rows()
	width := input.Cols()

	data := make([][]complex128, height)
	for y := 0; y < height; y++ {
		data[y] = make([]complex128, width)
		for x := 0; x < width; x++ {
			grayColor := float64(uint16(input.GetShortAt(y, x)))
			data[y][x] = complex(grayColor, 0)
		}
	}

	// 进行二维DFT
	log.Println("Performing 2D DFT...")
	dft := fft.FFT2(data)
	// 应用低通滤波器
	log.Println("Applying low-frequency-pass filter...")
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			if math.Abs(float64(x-width/2)) < float64(radius) || math.Abs(float64(y-height/2)) < float64(radius) {
				dft[y][x] = 0
			}
		}
	}

	// 进行二维逆DFT
	log.Println("Performing 2D inverse DFT...")
	idft := fft.IFFT2(dft)

	// 将浮点数数组转换回灰度图像
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			realPart := real(idft[y][x])
			if realPart < 0 {
				realPart = 0
			} else if realPart > 65535 {
				realPart = 65535
			}
			input.SetShortAt(y, x, int16(uint16(realPart)))
		}
	}

	return input
}
