-- 岩融冰结
local s,id,o=GetID()
function s.initial_effect(c)
    -- disable
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_ANNOUNCE)
	e1:SetType(EFFECT_TYPE_QUICK_O)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetRange(LOCATION_HAND)
	e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER)
    e1:SetCondition(s.con)
	e1:SetCost(s.cost)
	e1:SetTarget(s.target)
	c:RegisterEffect(e1)
	Duel.AddCustomActivityCounter(id,ACTIVITY_CHAIN,aux.FALSE)
end
function s.con(e,tp,eg,ep,ev,re,r,rp)
	local ph=Duel.GetCurrentPhase()
	return Duel.GetTurnPlayer()~=tp and (ph==PHASE_MAIN1 or ph==PHASE_MAIN2)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
    if chk==0 then return true end
    if chkc then return true end
    local ids={}
    local c=e:GetLabel()
	for i=1,c do
        Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CODE)
        local ac=Duel.AnnounceCard(tp)
        Duel.SetTargetParam(ac)
        table.insert(ids,ac)
    end 
    Duel.SetOperationInfo(0,CATEGORY_ANNOUNCE,nil,0,tp,0)
    e:SetOperation(s.op(ids))
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
    local count=s.count(tp)
    local maxc=math.floor(Duel.GetLP(tp)/1500)-count
    if chk==0 then return maxc>0 and e:GetHandler():IsAbleToGraveAsCost() end
    if maxc<=0 then return end
    --Duel.PayLPCost(1-tp, Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,LOCATION_ONFIELD)+1)
    --Duel.PayLPCost(1-tp, Duel.GetTurnCount())
    --Duel.PayLPCost(1-tp, Duel.GetCustomActivityCount(id,tp,ACTIVITY_CHAIN)+1)
    --Duel.PayLPCost(1-tp, Duel.GetCustomActivityCount(id,1-tp,ACTIVITY_CHAIN)+1)
    local t={}
	for i=1,maxc do t[i]=i end
	local a1=Duel.AnnounceNumber(tp,table.unpack(t))
    Duel.PayLPCost(tp,(a1+count)*1500)
    Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD)
    e:SetLabel(a1)
end
function s.count(tp)
    return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,LOCATION_ONFIELD)
        +Duel.GetTurnCount()-1 -- Turn starts in 1
        +Duel.GetCustomActivityCount(id,tp,ACTIVITY_CHAIN)
        +Duel.GetCustomActivityCount(id,1-tp,ACTIVITY_CHAIN)-1 -- Activate itself counts 1
end
function s.op(ids)
    return function (e,tp,eg,ep,ev,re,r,rp)
        for i,id in pairs(ids) do
            local e1=Effect.CreateEffect(e:GetHandler())
            e1:SetType(EFFECT_TYPE_FIELD)
            e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE)
            e1:SetCode(EFFECT_FORBIDDEN)
            e1:SetTargetRange(0x7f,0x7f)
            e1:SetTarget(s.bantg)
            e1:SetLabel(id)
            e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
            Duel.RegisterEffect(e1,tp)
        end
	end
end

function s.bantg(e,c)
	return c:IsCode(e:GetLabel()) and (not c:IsOnField() or c:GetRealFieldID()>e:GetFieldID())
end
