package main

import (
	"path/filepath"
	"strings"

	"github.com/airbusgeo/godal"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"starwiz.cn/sjy01/image-proc/pkg/fusion"
	producer "starwiz.cn/sjy01/image-proc/pkg/producer"
)

var (
	panImage  string
	mssImage  string
	outputDir string
	fusReport string
	fusMethod int
	weight    float32
)

var fusCmd = &cobra.Command{
	Use:   "fus",
	Short: "use GDAL_Pansharpen to merge PAN and MSS images",
	Run: func(cmd *cobra.Command, args []string) {
		initFUSParams()

		fusedTiff := filepath.Base(mssImage)
		fusedTiff = strings.Replace(fusedTiff, "MSS", "FUS", -1)
		id := strings.TrimSuffix(fusedTiff, filepath.Ext(fusedTiff))
		if fusReport == "" {
			fusReport = filepath.Join(outputDir, id+"_report.xml")
		}

		godal.RegisterAll()

		// err := producer.GDALPansharpen(panImage, mssImage, filepath.Join(outputDir, fusedTiff))
		// if err != nil {
		// 	logrus.Fatal(err)
		// }

		err := fusion.Pansharpen(panImage, mssImage,
			filepath.Join(outputDir, fusedTiff),
			fusion.PansharpenMethod(fusMethod),
			weight)
		if err != nil {
			logrus.Fatal(err)
		}

		producer.GTiffToJPG(filepath.Join(outputDir, fusedTiff), filepath.Join(outputDir, id+".jpg"), "FUS", true)

		var report producer.Report
		report.Satellite = "SJY01"
		report.Sensor = "FUS"
		report.Scenes = append(report.Scenes, producer.ReportScene{
			TiffData:    filepath.Join(outputDir, fusedTiff),
			BrowserData: filepath.Join(outputDir, id+".jpg"),
		})
		producer.WriteReport(&report, fusReport)
	},
}

func init() {
	rootCmd.AddCommand(fusCmd)

	fusCmd.Flags().StringVarP(&panImage, "pan", "p", "", "path to the PAN image")
	fusCmd.Flags().StringVarP(&mssImage, "mss", "m", "", "path to the MSS image")
	fusCmd.Flags().StringVarP(&outputDir, "output", "o", "", "path to the output directory")
	fusCmd.Flags().StringVarP(&paramsXML, "params", "x", "", "path to the XML file containing parameters for GDAL_Pansharpen")
	fusCmd.Flags().IntVarP(&fusMethod, "method", "t", int(fusion.ESRI), "method to use for fusion (5: IHS, 3: ESRI 1: brovey)")
	fusCmd.Flags().Float32VarP(&weight, "weight", "w", 0.1, "weight of the MSS image in the fusion (0-1)")
}

func initFUSParams() {
	if paramsXML == "" {
		return
	}

	task, err := producer.ParseXMLFUSTask(paramsXML)
	if err != nil {
		logrus.Fatal(err)
	}

	panImage = task.InputFileList.PanTiff
	mssImage = task.InputFileList.MssTiff
	outputDir = task.Params.OutputPath
	fusReport = task.Params.ReportFile
}
