package actions

import (
	"dk/internal/models/items"
	"dk/internal/models/users"
)

// UserEquipItem equips a given item onto a user. This overwrites any
// previously equipped item in the slot. Does not save.
func UserEquipItem(user *users.User, item *items.Item) {
	slotInUse := false
	if item.Type == items.TypeWeapon && user.WeaponID != 0 {
		slotInUse = true
	}
	if item.Type == items.TypeArmor && user.ArmorID != 0 {
		slotInUse = true
	}
	if item.Type == items.TypeShield && user.ShieldID != 0 {
		slotInUse = true
	}

	var oldItem *items.Item
	if slotInUse && item.Type == items.TypeWeapon {
		oldItem, _ = items.Find(user.WeaponID)
	} else if slotInUse && item.Type == items.TypeArmor {
		oldItem, _ = items.Find(user.ArmorID)
	} else if slotInUse && item.Type == items.TypeShield {
		oldItem, _ = items.Find(user.ShieldID)
	}

	if oldItem != nil {
		switch oldItem.Type {
		case items.TypeWeapon:
			user.Attack -= oldItem.Att
		case items.TypeArmor:
			user.Defense -= oldItem.Att
		case items.TypeShield:
			user.Defense -= oldItem.Att
		}
	}

	switch item.Type {
	case items.TypeWeapon:
		user.Attack += item.Att
		user.WeaponID = item.ID
		user.WeaponName = item.Name
	case items.TypeArmor:
		user.Defense += item.Att
		user.ArmorID = item.ID
		user.ArmorName = item.Name
	case items.TypeShield:
		user.Defense += item.Att
		user.ShieldID = item.ID
		user.ShieldName = item.Name
	}
}
