-- Rush Duel 仪式
RushDuel = RushDuel or {}
-- 当前的仪式效果
RushDuel.CurrentRitualEffect = nil
-- 额外的仪式检测
RushDuel.RitualExtraChecker = nil

-- 等级相同
RITUAL_LEVEL_EQUAL = 0x0
-- 等级超过
RITUAL_LEVEL_GREATER = 0x1
-- 攻击相同
RITUAL_ATTACK_EQUAL = 0x2
-- 攻击超过
RITUAL_ATTACK_GREATER = 0x3

-- 添加仪式手续
function RushDuel.AddRitualProcedure(card)
    if card:IsStatus(STATUS_COPYING_EFFECT) then
        return
    end
    local e = Effect.CreateEffect(card)
    e:SetType(EFFECT_TYPE_SINGLE)
    e:SetCode(EFFECT_REMOVE_TYPE)
    e:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE + EFFECT_FLAG_SET_AVAILABLE)
    e:SetRange(0xff)
    e:SetValue(TYPE_FUSION)
    card:RegisterEffect(e)
end

-- 创建效果: 仪式术/仪式 召唤
function RushDuel.CreateRitualEffect(card, type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, mat_move, target_action, operation_action, limit_action, including_self, self_leave)
    local self_range = s_range or 0
    local opponent_range = o_range or 0
    local move = mat_move or RushDuel.RitualToGrave
    local include = including_self or false
    local leave = self_leave or false
    local e = Effect.CreateEffect(card)
    e:SetTarget(RushDuel.RitualTarget(type, matfilter, spfilter, exfilter, self_range, opponent_range, mat_check, include, leave, target_action))
    e:SetOperation(RushDuel.RitualOperation(type, matfilter, spfilter, exfilter, self_range, opponent_range, mat_check, move, include, leave, operation_action, limit_action))
    return e
end
-- 仪式召唤 - 素材过滤
function RushDuel.RitualMaterialFilter(c, type, filter, e)
    local ext = true
    if type == RITUAL_LEVEL_EQUAL or type == RITUAL_LEVEL_GREATER then
        ext = c:IsLevelAbove(1)
    elseif type == RITUAL_ATTACK_EQUAL or type == RITUAL_ATTACK_GREATER then
        ext = c:IsAttackAbove(1)
    end
    return ext and (not filter or filter(c)) and (not e or not c:IsImmuneToEffect(e))
end
-- 仪式召唤 - 仪式召唤的怪兽过滤
function RushDuel.RitualSpecialSummonFilter(c, e, tp, type, mat, f, gc, chkf, filter)
    RushDuel.CurrentRitualEffect = e
    local res = c:GetType() & 0x81 == 0x81 and (not filter or filter(c, e, tp, mat, f, chkf)) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_RITUAL, tp, false, false) and
                    RushDuel.CheckRitualMaterial(tp, c, type, mat, gc)
    RushDuel.CurrentRitualEffect = nil
    return res
end
-- 仪式召唤 - 获取可用的仪式素材
function RushDuel.GetRitualMaterial(tp, rc, type, mat)
    local mg = mat:Filter(Card.IsCanBeRitualMaterial, rc, rc)
    if rc.mat_filter then
        mg = mg:Filter(rc.mat_filter, rc, tp)
    end
    local max = #mg
    if type == RITUAL_LEVEL_EQUAL or type == RITUAL_LEVEL_GREATER then
        max = rc:GetLevel()
    end
    return mg, max
end
-- 仪式召唤 - 检测仪式素材
function RushDuel.CheckRitualMaterial(tp, rc, type, mat, gc)
    local mg, max = RushDuel.GetRitualMaterial(tp, rc, type, mat)
    Auxiliary.GCheckAdditional = RushDuel.RitualCheckAdditional(rc, type)
    local res = mg:CheckSubGroup(RushDuel.RitualChecker, 1, max, rc, tp, type, gc)
    Auxiliary.GCheckAdditional = nil
    return res
end
-- 仪式召唤 - 选择仪式素材
function RushDuel.SelectRitualMaterial(tp, rc, type, mat, gc)
    local mg, max = RushDuel.GetRitualMaterial(tp, rc, type, mat)
    Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_RITUAL_MATERIAL)
    Auxiliary.GCheckAdditional = RushDuel.RitualCheckAdditional(rc, type)
    local sg = mg:SelectSubGroup(tp, RushDuel.RitualChecker, true, 1, max, rc, tp, type, gc)
    Auxiliary.GCheckAdditional = nil
    return sg
end
-- 仪式召唤 - 素材不能超过必要的数量
function RushDuel.RitualCheckAdditional(rc, type)
    local lv = rc:GetLevel()
    local atk = rc:GetAttack()
    if type == RITUAL_LEVEL_EQUAL then
        return function(g)
            return (not Auxiliary.RGCheckAdditional or Auxiliary.RGCheckAdditional(g)) and g:GetSum(Auxiliary.RitualCheckAdditionalLevel, rc) <= lv
        end
    elseif type == RITUAL_LEVEL_GREATER then
        return function(g, ec)
            if ec then
                return (not Auxiliary.RGCheckAdditional or Auxiliary.RGCheckAdditional(g, ec)) and g:GetSum(Auxiliary.RitualCheckAdditionalLevel, rc) - Auxiliary.RitualCheckAdditionalLevel(ec, rc) <=
                           lv
            else
                return not Auxiliary.RGCheckAdditional or Auxiliary.RGCheckAdditional(g)
            end
        end
    elseif type == RITUAL_ATTACK_EQUAL then
        return function(g)
            return (not aux.RGCheckAdditional or aux.RGCheckAdditional(g)) and g:GetSum(Auxiliary.GetCappedAttack) <= atk
        end
    elseif type == RITUAL_ATTACK_GREATER then
        return function(g, ec)
            if atk == 0 then
                return #g <= 1
            end
            if ec then
                return (not Auxiliary.RGCheckAdditional or Auxiliary.RGCheckAdditional(g, ec)) and g:GetSum(Auxiliary.GetCappedAttack) - Auxiliary.GetCappedAttack(ec) <= atk
            else
                return not Auxiliary.RGCheckAdditional or Auxiliary.RGCheckAdditional(g)
            end
        end
    end
end
-- 仪式召唤 - 仪式素材检测
function RushDuel.RitualChecker(mg, rc, tp, type, gc)
    if gc and not mg:IsContains(gc) then
        return false
    elseif rc.mat_group_check and not rc.mat_group_check(mg, tp) then
        return false
    elseif RushDuel.RitualExtraChecker and not RushDuel.RitualExtraChecker(mg, tp, rc) then
        return false
    elseif Auxiliary.RCheckAdditional and not Auxiliary.RCheckAdditional(tp, mg, rc) then
        return false
    else
        if type == RITUAL_LEVEL_EQUAL then
            return mg:CheckWithSumEqual(Card.GetRitualLevel, rc:GetLevel(), #mg, #mg, rc)
        elseif type == RITUAL_LEVEL_GREATER then
            Duel.SetSelectedCard(mg)
            return mg:CheckWithSumGreater(Card.GetRitualLevel, rc:GetLevel(), rc)
        elseif type == RITUAL_ATTACK_EQUAL then
            return mg:CheckWithSumEqual(Card.GetAttack, rc:GetAttack(), #mg, #mg, rc)
        elseif type == RITUAL_ATTACK_GREATER then
            Duel.SetSelectedCard(mg)
            return mg:CheckWithSumGreater(Card.GetAttack, rc:GetAttack(), rc)
        end
    end
    return false
end
-- 仪式召唤 - 确认素材过滤
function RushDuel.ConfirmCardFilter(c)
    return c:IsLocation(LOCATION_HAND) or (c:IsLocation(LOCATION_MZONE) and c:IsFacedown())
end
-- 仪式召唤 - 获取仪式素材与仪式怪兽
function RushDuel.GetRitualSummonData(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, including_self, self_leave, except, effect)
    local chkf = tp
    if except and self_leave then
        except:AddCard(e:GetHandler())
    elseif self_leave then
        except = e:GetHandler()
    end
    local mg = Duel.GetRitualMaterial(tp):Filter(RushDuel.RitualMaterialFilter, except, type, matfilter, effect)
    if s_range ~= 0 or o_range ~= 0 then
        local ext = Duel.GetMatchingGroup(Auxiliary.NecroValleyFilter(exfilter), tp, s_range, o_range, except, effect)
        mg:Merge(ext:Filter(RushDuel.RitualMaterialFilter, nil, type))
    end
    local gc = nil
    if including_self then
        gc = e:GetHandler()
    end
    local sg = Duel.GetMatchingGroup(RushDuel.RitualSpecialSummonFilter, tp, LOCATION_EXTRA, 0, nil, e, tp, type, mg, nil, gc, chkf, spfilter)
    local list = {}
    local ritualable = false
    if #sg > 0 then
        table.insert(list, {nil, mg, sg})
        ritualable = true
    end
    return ritualable, list, chkf, gc
end
-- 仪式召唤 - 进行仪式召唤
function RushDuel.ExecuteRitualSummon(e, tp, type, list, chkf, gc, mat_move, cancelable)
    local sg = Group.CreateGroup()
    for _, data in ipairs(list) do
        sg:Merge(data[3])
    end
    ::cancel::
    local rc = nil
    Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
    if cancelable then
        local g = RushDuel.SelectGroup(tp, sg, 1, 1)
        if not g then
            return nil
        else
            rc = g:GetFirst()
        end
    else
        rc = sg:Select(tp, 1, 1, nil):GetFirst()
    end
    local options = {}
    for _, data in ipairs(list) do
        local ce, sg = data[1], data[3]
        if sg:IsContains(rc) then
            if ce then
                table.insert(options, {true, ce:GetDescription(), data})
            else
                table.insert(options, {true, 1168, data})
            end
        end
    end
    local data = options[1][3]
    if #options > 1 then
        data = Auxiliary.SelectFromOptions(tp, table.unpack(options))
    end
    local ce, mg = data[1], data[2]
    RushDuel.CurrentRitualEffect = e
    local mat = RushDuel.SelectRitualMaterial(tp, rc, type, mg, gc)
    RushDuel.CurrentRitualEffect = nil
    if not mat then
        goto cancel
    end
    local cg = mat:Filter(RushDuel.ConfirmCardFilter, nil)
    if #cg > 0 then
        Duel.ConfirmCards(1 - tp, cg)
    end
    rc:SetMaterial(mat)
    if ce then
        local fop = ce:GetOperation()
        fop(ce, e, tp, rc, mat)
    else
        mat_move(tp, mat, e)
    end
    Duel.BreakEffect()
    Duel.SpecialSummon(rc, SUMMON_TYPE_RITUAL, tp, tp, false, false, POS_FACEUP)
    rc:CompleteProcedure()
    return rc, mat
end
-- 判断条件: 怪兽区域判断
function RushDuel.RitualCheckLocation(e, self_leave, extra)
    return function(sg, tp, rc)
        local mg = nil
        if extra and not extra(tp, sg, rc) then
            return false
        elseif self_leave then
            mg = Group.FromCards(e:GetHandler())
            mg:Merge(sg)
        else
            mg = sg
        end
        if rc:IsLocation(LOCATION_EXTRA) then
            return Duel.GetLocationCountFromEx(tp, tp, mg, rc) > 0
        else
            return Duel.GetMZoneCount(tp, mg) > 0
        end
    end
end
-- 判断条件: 是否可以进行仪式召唤
function RushDuel.IsCanRitualSummon(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, including_self, self_leave, except)
    RushDuel.RitualExtraChecker = RushDuel.RitualCheckLocation(e, self_leave, mat_check)
    local ritualable = RushDuel.GetRitualSummonData(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, including_self, self_leave, except)
    RushDuel.RitualExtraChecker = nil
    return ritualable
end
-- 仪式召唤 - 目标
function RushDuel.RitualTarget(type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, including_self, self_leave, target_action)
    return function(e, tp, eg, ep, ev, re, r, rp, chk)
        if chk == 0 then
            return RushDuel.IsCanRitualSummon(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, including_self, self_leave, nil)
        end
        if action ~= nil then
            action(e, tp, eg, ep, ev, re, r, rp)
        end
        Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, nil, 1, tp, LOCATION_EXTRA)
    end
end
-- 仪式召唤 - 处理
function RushDuel.RitualOperation(type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, mat_move, including_self, self_leave, action, limit)
    return function(e, tp, eg, ep, ev, re, r, rp)
        RushDuel.RitualExtraChecker = RushDuel.RitualCheckLocation(e, self_leave, mat_check)
        local ritualable, list, chkf, gc = RushDuel.GetRitualSummonData(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, including_self, self_leave, nil, e)
        if ritualable then
            local fc, mat = RushDuel.ExecuteRitualSummon(e, tp, type, list, chkf, gc, mat_move)
            if action ~= nil then
                action(e, tp, eg, ep, ev, re, r, rp, mat, fc)
            end
        end
        RushDuel.RitualExtraChecker = nil
        if limit ~= nil then
            limit(e, tp, eg, ep, ev, re, r, rp)
        end
    end
end

-- 强制进行仪式召唤
function RushDuel.RitualSummon(type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, mat_move, e, tp, break_effect, including_self, self_leave)
    local include = including_self or false
    local leave = self_leave or false
    RushDuel.RitualExtraChecker = RushDuel.RitualCheckLocation(e, self_leave, mat_check)
    local ritualable, list, chkf, gc = RushDuel.GetRitualSummonData(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, include, leave, nil, e)
    local rc = nil
    if ritualable then
        if break_effect then
            Duel.BreakEffect()
        end
        rc = RushDuel.ExecuteRitualSummon(e, tp, type, list, chkf, gc, mat_move)
    end
    RushDuel.RitualExtraChecker = nil
    return rc
end

-- 可以进行仪式召唤
function RushDuel.CanRitualSummon(desc, type, matfilter, spfilter, exfilter, s_range, o_range, mat_check, mat_move, e, tp, break_effect, including_self, self_leave)
    local include = including_self or false
    local leave = self_leave or false
    RushDuel.RitualExtraChecker = RushDuel.RitualCheckLocation(e, self_leave, mat_check)
    local ritualable, list, chkf, gc = RushDuel.GetRitualSummonData(e, tp, type, matfilter, spfilter, exfilter, s_range, o_range, include, leave, nil, e)
    local rc = nil
    ::cancel::
    if ritualable and Duel.SelectYesNo(tp, desc) then
        if break_effect then
            Duel.BreakEffect()
        end
        rc = RushDuel.ExecuteRitualSummon(e, tp, type, list, chkf, gc, mat_move, true)
        if not rc then
            goto cancel
        end
    end
    RushDuel.RitualExtraChecker = nil
    return rc
end

-- 素材去向: 墓地
function RushDuel.RitualToGrave(tp, mat)
    Duel.SendtoGrave(mat, REASON_EFFECT + REASON_MATERIAL + REASON_RITUAL)
end
-- 素材去向: 卡组
function RushDuel.RitualToDeck(tp, mat)
    local g = mat:Filter(Card.IsFacedown, nil)
    if g:GetCount() > 0 then
        Duel.ConfirmCards(1 - tp, g)
    end
    Duel.SendtoDeck(mat, nil, SEQ_DECKSHUFFLE, REASON_EFFECT + REASON_MATERIAL + REASON_RITUAL)
end
-- 素材去向: 卡组下面
function RushDuel.RitualToDeckBottom(tp, mat)
    local g = mat:Filter(Card.IsFacedown, nil)
    if g:GetCount() > 0 then
        Duel.ConfirmCards(1 - tp, g)
    end
    Auxiliary.PlaceCardsOnDeckBottom(tp, mat, REASON_EFFECT + REASON_MATERIAL + REASON_RITUAL)
end
