package producer

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/airbusgeo/godal"
	log "github.com/sirupsen/logrus"
	"gocv.io/x/gocv"
	"starwiz.cn/sjy01/image-proc/pkg/utils"
)

func (r *Registrator) SaveOriginalPanToGDALGTiff(tiffFile string) error {
	err := utils.SavePanToGDALGTiff(r.PanImage, 0, 0, tiffFile, PanResolution)
	if err != nil {
		return err
	}

	return nil
}

func (r *Registrator) SaveRegisteredMssToGDALGTiff(tiffFile string) error {
	r.rgbirImage = gocv.NewMat()
	gocv.Merge(r.registeredMssImages[:], &r.rgbirImage)

	err := utils.SaveBGRToGDALGTiff(r.rgbirImage,
		4, 0, 0, MssResolution,
		[]godal.ColorInterp{godal.CIBlue, godal.CIGreen, godal.CIRed, godal.CIUndefined},
		tiffFile)
	if err != nil {
		return err
	}

	return nil
}

func (r *Registrator) BytesToRaw(mssData []byte, filePath string) error {
	f, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
	if err != nil {
		return err
	}
	w := bufio.NewWriter(f)
	w.Write(mssData)

	return nil
}

func (r *Registrator) SaveRegisteredMssToRaw(raw string) error {
	f, err := os.OpenFile(raw, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
	if err != nil {
		return err
	}

	var mssData [4][]byte
	for i := 0; i < MssBands; i++ {
		mssData[i] = r.registeredMssImages[i].ToBytes()
	}

	width := r.registeredMssImages[0].Cols() * PixelBytes
	height := r.registeredMssImages[0].Rows()
	log.Println("Writing registered MSS to RAW file...", len(mssData[0])*4)
	log.Println("width:", width)
	log.Println("height:", height)
	w := bufio.NewWriter(f)
	for row := 0; row < height; row++ {
		w.Write(mssData[0][row*width : (row+1)*width])
		w.Write(mssData[1][row*width : (row+1)*width])
		w.Write(mssData[2][row*width : (row+1)*width])
		w.Write(mssData[3][row*width : (row+1)*width])
	}

	hdr := EnviHdr{
		Samples: 4 * width / PixelBytes,
		Lines:   height,
		Bands:   1,
	}

	hdrFile := filepath.Join(filepath.Dir(raw),
		fmt.Sprintf("%s.HDR", strings.TrimSuffix(filepath.Base(raw), filepath.Ext(raw))),
	)
	hdr.Write(hdrFile)

	return nil
}

func (r *Registrator) Report() error {
	return WriteReport(&r.report, r.Params.ReportFile)
}

func (r *Registrator) rpcKeywordInTif() {
	// GDAL库对应的RPC关键词
	// keys := []string{
	// 	"ERR_BIAS", "ERR_RAND",
	// 	"LINE_OFF", "SAMP_OFF",
	// 	"LAT_OFF", "LONG_OFF", "HEIGHT_OFF",
	// 	"LINE_SCALE", "SAMP_SCALE",
	// 	"LAT_SCALE", "LONG_SCALE", "HEIGHT_SCALE",
	// 	"LINE_NUM_COEFF", "LINE_DEN_COEFF",
	// 	"SAMP_NUM_COEFF", "SAMP_DEN_COEFF",
	// }

	// values := map[string]string{}

}
