-- 冥府的使者 凯茵
local s,id,o=GetID()
function s.initial_effect(c)
    -- destroy
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_ANNOUNCE)
	e1:SetType(EFFECT_TYPE_QUICK_O)
	e1:SetCode(EVENT_CHAINING)
	e1:SetRange(LOCATION_HAND)
	e1:SetCost(s.cost)
	e1:SetTarget(s.target)
	e1:SetOperation(s.op)
	c:RegisterEffect(e1)
	local e2=Effect.CreateEffect(c)
	e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
	e2:SetCode(EVENT_TO_GRAVE)
	e2:SetProperty(EFFECT_FLAG_DELAY)
	e2:SetTarget(s.sgtg)
	e2:SetOperation(s.sgop)
	c:RegisterEffect(e2)
	if not s.gf then
		s.gf=true
		local ge1=Effect.CreateEffect(c)
		ge1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
		ge1:SetCode(EVENT_TO_GRAVE)
		ge1:SetCondition(s.descon)
		ge1:SetOperation(s.desop)
		Duel.RegisterEffect(ge1,0)
	end
end
function s.filter(c)
	return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsPosition(POS_FACEUP)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
	local c=e:GetHandler()
	if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_ONFIELD,0,1,nil) end
	local sg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_ONFIELD,0,c)
	Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,#sg,0,0)
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
	local c=e:GetHandler()
	if chk==0 then return c:IsDiscardable() end
	Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD)
end
function s.op(e,tp,eg,ep,ev,re,r,rp)
	local sg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_ONFIELD,0,nil)
	Duel.Destroy(sg,REASON_EFFECT)
end

function s.sgtg(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then
		local ct=Duel.GetFlagEffectLabel(tp,id)
		return Duel.GetMatchingGroupCount(aux.TRUE,tp,LOCATION_ONFIELD,0,nil)==0 
			and ct and ct>0
			and Duel.IsExistingMatchingCard(s.sgfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil)
	end
end

function s.sgfilter(c)
	return c:IsAbleToGrave()
end

function s.sgop(e,tp,eg,ep,ev,re,r,rp)
	local ct=Duel.GetFlagEffectLabel(tp,id)
	if ct and ct>0 then	
		Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
		local g=Duel.SelectTarget(tp,s.sgfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,ct,nil)
		Duel.SendtoGrave(g,REASON_EFFECT)
	end
end

function s.descon(e,tp,eg,ep,ev,re,r,rp)
	local c=eg:GetFirst()
	while c do
		if bit.band(r,REASON_DESTROY)~=0
			and c:IsPreviousLocation(LOCATION_ONFIELD)
			and (c:IsType(TYPE_SPELL) or c:IsType(TYPE_TRAP)) then
			return true
		end
		c=eg:GetNext()
	end
	return false
end

function s.desop(e,tp,eg,ep,ev,re,r,rp)
	local c=eg:GetFirst()
	while c do
		local p=c:GetOwner()
		local ct=Duel.GetFlagEffectLabel(p,id)
		if ct==nil then
			Duel.RegisterFlagEffect(p,id,RESET_PHASE+PHASE_END,0,1,1)
		else
			Duel.SetFlagEffectLabel(p,id,ct+1)
		end
		c=eg:GetNext()
	end
end