package model

import "strings"

type GroupMode int

const (
	Equality        = GroupMode(1 << 5)
	Filesharing     = GroupMode(1 << 6)
	AnyoneCanInvite = GroupMode(1 << 9)
	HideByDefault   = GroupMode(1 << 13)
	OpenGroup       = GroupMode(1 << 15)
	Slow            = GroupMode(1 << 19)
	VoiceOnly       = GroupMode(1 << 22)
	WriteOnly       = GroupMode(1 << 23)
)

func (gm GroupMode) IsSet(mode GroupMode) bool {
	return gm&mode >= 1
}

func (gm GroupMode) IsNotSet(mode GroupMode) bool {
	return gm&mode == 0
}

func (gm GroupMode) ToString() string {
	mode := ""
	if gm > 0 {
		if (gm & Equality) > 0 {
			mode += "e"
		}
		if (gm & Filesharing) > 0 {
			mode += "f"
		}
		if (gm & AnyoneCanInvite) > 0 {
			mode += "i"
		}
		if (gm & HideByDefault) > 0 {
			mode += "m"
		}
		if (gm & OpenGroup) > 0 {
			mode += "o"
		}
		if (gm & Slow) > 0 {
			mode += "s"
		}
		if (gm & VoiceOnly) > 0 {
			mode += "v"
		}
		if (gm & WriteOnly) > 0 {
			mode += "w"
		}

	}
	return mode
}

// MarshalText implements encoding.TextMarshaler.
func (gm GroupMode) MarshalText() ([]byte, error) {
	return []byte(gm.ToString()), nil
}

// UnmarshalText implements encoding.TextUnmarshaler.
func (gm *GroupMode) UnmarshalText(text []byte) error {
	str := string(text)
	if strings.Contains(str, "e") {
		*gm |= Equality
	}
	if strings.Contains(str, "f") {
		*gm |= Filesharing
	}
	if strings.Contains(str, "i") {
		*gm |= AnyoneCanInvite
	}
	if strings.Contains(str, "m") {
		*gm |= HideByDefault
	}
	if strings.Contains(str, "o") {
		*gm |= OpenGroup
	}
	if strings.Contains(str, "s") {
		*gm |= Slow
	}
	if strings.Contains(str, "v") {
		*gm |= VoiceOnly
	}
	if strings.Contains(str, "w") {
		*gm |= WriteOnly
	}
	return nil
}
