package main

import (
	"sort"
)

type Initiative []*Group

func (in Initiative) Len() int {
	return len(in)
}

func (in Initiative) Swap(i, j int) {
	in[i], in[j] = in[j], in[i]
}

func (in Initiative) Less(i, j int) bool {
	return in[i].Initiative > in[j].Initiative
}

func (in Initiative) Attack() {
	sort.Sort(in)

	for _, group := range in {
		if group.Units > 0 && group.Target != nil && group.Target.Units > 0 {
			group.Target.Units -= group.DamageDealt(group.Target) / group.Target.HitPoints
		}
		if group.Target != nil {
			group.Target.Attacker = nil
			group.Target = nil
		}
	}
}

func (in *Initiative) Clean() {
	c := (*in)[:0]
	for _, g := range *in {
		if g.Units > 0 {
			c = append(c, g)
		}
	}
	sort.Sort(c)
	*in = c
}
