package mysql

import (
	"github.com/juju/errors"
	gmysql "github.com/siddontang/go-mysql/mysql"
)

// GTIDSet wraps mysql.MysqlGTIDSet
// todo: wrap mysql.GTIDSet
type GTIDSet struct {
	*gmysql.MysqlGTIDSet
}

// ParseGTIDSet parses gtid string into GTIDSet.
func ParseGTIDSet(gtidStr string) (GTIDSet, error) {
	gs, err := gmysql.ParseMysqlGTIDSet(gtidStr)
	if err != nil {
		return GTIDSet{}, errors.Trace(err)
	}

	return GTIDSet{gs.(*gmysql.MysqlGTIDSet)}, nil
}

// Delete deletes gtid from gtid set.
func (g GTIDSet) Delete(uuid string) {
	delete(g.Sets, uuid)
}

// ContainUUID checks gtid in gtid set.
func (g GTIDSet) ContainUUID(uuid string) bool {
	_, ok := g.Sets[uuid]
	return ok
}

// Get returns uuid set.
func (g GTIDSet) Get(uuid string) *gmysql.UUIDSet {
	return g.Sets[uuid]
}

// All returns all uuid set.
func (g GTIDSet) All() map[string]*gmysql.UUIDSet {
	return g.Sets
}

// Len returns the length of gtid set.
func (g GTIDSet) Len() int {
	return len(g.Sets)
}

func (g GTIDSet) String() string {
	if g.MysqlGTIDSet == nil {
		return "<nil>"
	}

	return g.MysqlGTIDSet.String()
}

// IsNil check if MysqlGTIDSet is nil.
func (g GTIDSet) IsNil() bool {
	return g.MysqlGTIDSet == nil
}
