-- 暗黑界的召集
local s,id,o=GetID()
function s.initial_effect(c)
	--Activate
	local e1=Effect.CreateEffect(c)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetHintTiming(0,TIMING_END_PHASE)
	c:RegisterEffect(e1)

	--collect
	local e2=Effect.CreateEffect(c)
	e2:SetDescription(aux.Stringid(id,0))
	e2:SetCategory(CATEGORY_SEARCH+CATEGORY_LEAVE_GRAVE)
	e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
	e2:SetCode(EVENT_DISCARD)
	e2:SetRange(LOCATION_SZONE)
	e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
	e2:SetCountLimit(1,id)
	e2:SetCondition(s.cocon)
	e2:SetOperation(s.coop)
	c:RegisterEffect(e2)
	--collect spell
	local e3=e2:Clone()
	e3:SetDescription(aux.Stringid(id,3))
	e3:SetCondition(s.cocon2)
	e3:SetOperation(s.coop2)
	c:RegisterEffect(e3)
end

function s.cofilter(c,tp,re)
	local rc=re:GetHandler()
	return c:IsSetCard(0x6)
		and c:IsReason(REASON_EFFECT)
		and c:IsPreviousLocation(LOCATION_HAND)
		and c:IsPreviousControler(tp)
end
function s.monfilter(c)
	return c:IsType(TYPE_MONSTER)
end
function s.spellfilter(c,tp)
	return c:IsType(TYPE_SPELL) or c:IsType(TYPE_TRAP) and c:IsPreviousControler(tp) and c:IsLocation(LOCATION_GRAVE)
end
function s.exist3(c,tp)
	return Duel.GetMatchingGroup(aux.NecroValleyFilter(Card.IsCode),tp,0x35,0,nil,c:GetCode()):__len()>=3
end
function s.cocon(e,tp,eg,ep,ev,re,r,rp)
	return re and eg:IsExists(aux.AND(s.cofilter,s.monfilter,s.exist3),1,nil,tp,re)
end
function s.cocon2(e,tp,eg,ep,ev,re,r,rp)
	return re and eg:IsExists(aux.AND(s.cofilter,s.spellfilter),1,nil,tp,re)
end
function s.coop(e,tp,eg,ep,ev,re,r,rp)
	if Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil,REASON_EFFECT)
		and Duel.SelectOption(tp,aux.Stringid(id,1),aux.Stringid(id,2))==0 then
		Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_EFFECT+REASON_DISCARD)
	else
		Duel.PayLPCost(tp,math.floor(Duel.GetLP(tp)/2))
	end
	local ec=eg:GetFirst()
	while ec do
		if s.monfilter(ec) then 
			local g=Duel.GetMatchingGroup(aux.NecroValleyFilter(Card.IsCode),tp,0x35,0,nil,ec:GetCode())
			g:RemoveCard(ec)
			if #g>=2 then
				g=g:Select(tp,2,2,nil)
			end
			Duel.SendtoHand(g,nil,REASON_EFFECT)
		end
		ec=eg:GetNext()
	end
end
function s.coop2(e,tp,eg,ep,ev,re,r,rp)
	local cg=eg:Filter(s.spellfilter,nil,e)
	local n=Duel.SSet(tp,cg)
	if n>0 then
		Duel.DiscardHand(tp,aux.TRUE,n,n,REASON_EFFECT+REASON_DISCARD)
	end
end