package auxilary

import (
	"fmt"
	"os"
)

// PAN 16 行 / MSS 4 行 图像对应 1 行辅助数据记录，需要单独计算图像行时间
type ImageTime struct {
	auxT []*auxT
}

type auxT struct {
	Tutc float64
	Row  int
}

func NewImageTime(aps []*AuxPlatform) *ImageTime {
	it := &ImageTime{
		auxT: make([]*auxT, 0),
	}
	it.Extract(aps)
	return it
}

func (it *ImageTime) Extract(aps []*AuxPlatform) {
	var sec, microsec uint32
	for i, ap := range aps {
		if ap.UTCTimeSec != sec || ap.Microsecond != microsec {
			sec, microsec = ap.UTCTimeSec, ap.Microsecond
			t := float64(ap.UTCTimeSec) + float64(ReferenceTime2000) + float64(ap.Microsecond)/1e6
			it.auxT = append(it.auxT, &auxT{Tutc: t, Row: i})
		}
	}
}

// Interp 内插出成像时刻
// 参数: imgrow 图像行号 cross 图像跨度 aps 辅助平台列表
// 返回值: 成像时刻(UTC seconds)
func (it *ImageTime) Interp0(imgrow int, cross int) (float64, float64) {
	// 内插出成像时刻
	u := int(imgrow / cross)
	var u1, u2 *auxT
	for i, a := range it.auxT {
		if a.Row > u {
			u1 = it.auxT[i-1]
			u2 = a
			break
		}
	}
	dt := (u2.Tutc - u1.Tutc) / float64(cross*(u2.Row-u1.Row))
	t := u1.Tutc + dt*float64(imgrow-u1.Row*cross)
	return t, dt
}

func (it *ImageTime) Interp(imgrow int, cross int) (float64, float64) {
	n := len(it.auxT)
	rCnt := (it.auxT[n-1].Row-it.auxT[0].Row)*cross + 1
	dt := (it.auxT[n-1].Tutc - it.auxT[0].Tutc) / float64(rCnt)
	t := it.auxT[0].Tutc + dt*float64(imgrow)
	return t, dt
}

func (it *ImageTime) Store(imgtimeFile string) error {
	f, err := os.Create(imgtimeFile)
	if err != nil {
		return err
	}
	defer f.Close()
	for _, a := range it.auxT {
		s := fmt.Sprintf("%.6f\t%d\n", a.Tutc, a.Row)
		f.WriteString(s)
	}
	return nil
}
