package binlog

import (
	"b612.me/mysql/gtid"
	"encoding/binary"
	"io"
	"os"
)

func GetGtidOfBinlog(binlogPath string) (gtidDesc string, err error) {
	file, err := os.Open(binlogPath)
	if nil != err {
		return "", err
	}
	defer file.Close()

	p := uint32(4)
	headerBs := make([]byte, 19)
	gtidBs := make([]byte, 25)
	myGtid, err := gtid.Parse(gtidDesc)
	if err != nil {
		return gtidDesc, err
	}
	for {
		if _, err := file.Seek(int64(p), 0); nil != err {
			if "EOF" == err.Error() {
				break
			}
			return myGtid.String(), err
		}

		if _, err := io.ReadFull(file, headerBs); nil != err {
			if "EOF" == err.Error() {
				break
			}
			return myGtid.String(), err
		}

		length := binary.LittleEndian.Uint32(headerBs[9:13])
		eventType := int(headerBs[4])

		if GTID_LOG_EVENT != eventType {
			p += length
			continue
		}

		if _, err := io.ReadFull(file, gtidBs); nil != err {
			if "EOF" == err.Error() {
				break
			}
			return myGtid.String(), err
		}

		uuid := bytesToUuid(gtidBs[1:17])
		number := bytesToUint64(gtidBs[17:])
		if err = myGtid.AddGtid(uuid, number); nil != err {
			return myGtid.String(), err
		}

		p += length
	}
	return myGtid.String(), nil
}
