--帝王的胎动
local s,id,o=GetID()
function s.initial_effect(c)
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_TOHAND)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetTarget(s.target)
	e1:SetOperation(s.activate)
	c:RegisterEffect(e1)
end

function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
    local n=s.scan_location(Card.IsAbleToHand,LOCATION_DECK,tp)
    local attrs=s.available_attributes(n)
	if chk==0 then return attrs>0 end
    e:SetLabel(Duel.AnnounceAttribute(tp,1,attrs))
	Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,4,tp,LOCATION_DECK)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
    local l=s.scan_location(Card.IsAbleToHand,LOCATION_DECK,tp)
    local attrs=s.available_attributes(l)
    local attr=e:GetLabel()
    if bit.band(attrs,attr)~=attr then return end
    local g=
        Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,attr,800)+
        Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,attr,2400)+
        Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,attr,2800)+
        Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,attr,3000)
    Duel.SendtoHand(g,nil,REASON_EFFECT)
    Duel.ConfirmCards(1-tp,g)
end

function s.filter(c,attr,atk)
    return c:IsAttribute(attr) and c:IsAttack(atk) and c:IsDefense(1000)
end

function s.available_attributes(n)
    return s.attribute_available(n, ATTRIBUTE_EARTH)
          +s.attribute_available(n, ATTRIBUTE_WATER)
          +s.attribute_available(n, ATTRIBUTE_FIRE)
          +s.attribute_available(n, ATTRIBUTE_WIND)
          +s.attribute_available(n, ATTRIBUTE_LIGHT)
          +s.attribute_available(n, ATTRIBUTE_DARK)
end

function s.attribute_available(n,attribute)
    local j=attribute*attribute*attribute*attribute*15
    if bit.band(n,j)==j then
        return attribute
    else
        return 0
    end
end

function s.scan_location(f,l,tp)
    local g=Duel.GetMatchingGroup(f,tp,l,0,nil)
    local n=0
    for c in aux.Next(g) do
        n=s.scan_card(c,n)
    end
    return n
end

function s.scan_card(c,n)
    -- 0000,0000,0000,0000,0000,0000
    --  暗   光   风    炎    水   地
    --  1   1   1   1
    -- 混帝 大帝 帝 侍从 
    if not c:IsDefense(1000) then return n end
    local bit=0
    if c:IsAttack(800) then bit=bit+1
    elseif c:IsAttack(2400) then bit=bit+2
    elseif c:IsAttack(2800) then bit=bit+4
    elseif c:IsAttack(3000) then bit=bit+8
    end
    if bit==0 then return n end
    local a=c:GetAttribute()
    while a>0 do
        local ca=a&(a-1)
        local cab=a-ca
        n=n|(cab*cab*cab*cab*bit)
        a=ca
    end
    return n
end
