local m=120254083
local cm=_G["c"..m]
cm.name="国王的贪欲"
function cm.initial_effect(c)
	--Activate
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_POSITION+CATEGORY_DRAW)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetCost(cm.cost)
	e1:SetTarget(cm.target)
	e1:SetOperation(cm.activate)
	c:RegisterEffect(e1)
end
--Activate
function cm.costfilter1(c)
	return c:IsLevelAbove(5) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FIEND) and c:IsAbleToGraveAsCost()
end
function cm.costfilter2(c)
	return c:IsLevelAbove(7) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FIEND) and c:IsAbleToDeckOrExtraAsCost()
end
function cm.costcheck(g)
	return RD.GroupAllCount(g,Card.IsLocation,1,LOCATION_HAND)
		or RD.GroupAllCount(g,Card.IsLocation,3,LOCATION_GRAVE)
end
function cm.filter(c)
	return c:IsPosition(POS_FACEUP_ATTACK) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FIEND) and RD.IsCanChangePosition(c)
end
function cm.cost(e,tp,eg,ep,ev,re,r,rp,chk)
	local g1=Duel.GetMatchingGroup(cm.costfilter1,tp,LOCATION_HAND,0,nil)
	local g2=Duel.GetMatchingGroup(cm.costfilter2,tp,LOCATION_GRAVE,0,nil)
	if chk==0 then return g1:GetCount()>0 or g2:GetCount()>2 end
	local sg
	if g1:GetCount()<1 then
		Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
		sg=g2:Select(tp,3,3,nil)
	elseif g2:GetCount()<3 then
		Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
		sg=g1:Select(tp,1,1,nil)
	else
		g1:Merge(g2)
		Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(m,1))
		sg=g1:SelectSubGroup(tp,cm.costcheck,false,1,3)
	end
	if sg:GetCount()==1 then
		Duel.SendtoGrave(sg,REASON_COST)
	else
		Duel.SendtoDeck(sg,nil,SEQ_DECKSHUFFLE,REASON_COST)
	end
end
function cm.target(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then return Duel.IsExistingMatchingCard(cm.filter,tp,LOCATION_MZONE,0,1,nil) end
	local g=Duel.GetMatchingGroup(cm.filter,tp,LOCATION_MZONE,0,nil)
	Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function cm.activate(e,tp,eg,ep,ev,re,r,rp)
	RD.SelectAndDoAction(HINTMSG_POSCHANGE,cm.filter,tp,LOCATION_MZONE,0,1,1,nil,function(g)
		if RD.ChangePosition(g,POS_FACEUP_DEFENSE)~=0 then
			RD.CanDraw(aux.Stringid(m,2),tp,2,true)
		end
	end)
end