package producer

import (
	"fmt"
	"path/filepath"

	"github.com/sirupsen/logrus"
	"starwiz.cn/sjy01/image-proc/pkg/payload"
	"starwiz.cn/sjy01/image-proc/pkg/rrc"
)

func (r *Registrator) DoRRCbyLUT(lutDir string) error {
	logrus.Printf("try to do RRC [%s]...", lutDir)
	lutPAN, err := rrc.LoadLUT(filepath.Join(lutDir, "B0.LUT"), 9344)
	if err != nil {
		logrus.Error("load pan gray table failed")
		return err
	}

	for y := 0; y < r.PanImage.Rows(); y++ {
		for x := 0; x < r.PanImage.Cols(); x++ {
			newGray := lutPAN[x][int(uint16(r.PanImage.GetShortAt(y, x)))]
			r.PanImage.SetShortAt(y, x, int16(newGray))
		}
	}

	for i := 0; i < 4; i++ {
		lutMSS, err := rrc.LoadLUT(filepath.Join(lutDir, fmt.Sprintf("B%d.LUT", i+1)), payload.MSS_PIXEL_WIDTH)
		if err != nil {
			logrus.Error("load mss gray table failed")
			return err
		}

		for y := 0; y < r.MssImages[i].Rows(); y++ {
			for x := 0; x < r.MssImages[i].Cols(); x++ {
				newGray := lutMSS[x][int(uint16(r.MssImages[i].GetShortAt(y, x)))]
				r.MssImages[i].SetShortAt(y, x, int16(newGray))
			}
		}
	}

	return nil
}

func (r *Registrator) DoMomentMatching() error {
	rrc.DoMomentMatching(r.PanImage)
	for i := 0; i < 4; i++ {
		rrc.DoMomentMatching(r.MssImages[i])
	}

	return nil
}
