local assets =
{
	Asset("ANIM", "anim/books.zip"),
	--Asset("SOUND", "sound/common.fsb"),
}
 
local prefabs =
{
    "tentacle",
    "splash_ocean",
    "book_fx"
}    

function tentaclesfn(inst, reader)

    return true    

end




function firefn(inst, reader)

	local num_lightnings =  4
	local numtentacles = 2
	local allow_use = false
	local sanity_delta = 0
	if reader.components.inventory:Has("papyrus", 2)
	or reader.components.inventory:Has("cutreeds", 3)
	or reader.components.inventory:Has("cutgrass", 9) then
		allow_use = true
		if reader.components.inventory:Has("cutgrass", 9) then
		    reader.components.inventory:ConsumeByName("cutgrass", 9)
			sanity_delta = 0.5
		elseif reader.components.inventory:Has("cutreeds", 4) then
		    reader.components.inventory:ConsumeByName("cutreeds", 4)
			num_lightnings = 12
			numtentacles = 4
			sanity_delta = 0.8
		elseif reader.components.inventory:Has("papyrus", 2) then
		    reader.components.inventory:ConsumeByName("papyrus", 2)
			num_lightnings = 16
			numtentacles = 6
			sanity_delta = 1.1
		end
	end
	
	if	allow_use == true then
 
    reader.components.sanity:DoDelta(-TUNING.SANITY_LARGE*sanity_delta)
    reader:StartThread(function()
        for k = 0, num_lightnings do

            local rad = math.random(10, 15)
            local angle = k*((4*PI)/num_lightnings)
            local pos = Vector3(reader.Transform:GetWorldPosition()) + Vector3(rad*math.cos(angle), 0, rad*math.sin(angle))
            GetSeasonManager():DoLightningStrike(pos)
            Sleep(math.random( .5, .8))
        end
    end)

	
    local pt = Vector3(reader.Transform:GetWorldPosition())


    reader.components.sanity:DoDelta(-TUNING.SANITY_HUGE)

    reader:StartThread(function()
        for k = 1, numtentacles do
        
            local theta = math.random() * 2 * PI
            local radius = math.random(6, 10)

            -- we have to special case this one because birds can't land on creep
            local result_offset = FindValidPositionByFan(theta, radius, 12, function(offset)
                local x,y,z = (pt + offset):Get()
                local ents = TheSim:FindEntities(x,y,z , 1)
                return not next(ents) 
            end)

            if result_offset then
                local tentacle = SpawnPrefab("tentacle")
                
                tentacle.Transform:SetPosition((pt + result_offset):Get())
                GetPlayer().components.playercontroller:ShakeCamera(reader, "FULL", 0.2, 0.02, .25, 40)
                
                --need a better effect
                local fx = SpawnPrefab("splash_ocean")
                local pos = pt + result_offset
                fx.Transform:SetPosition(pos.x, pos.y, pos.z)
                --PlayFX((pt + result_offset), "splash", "splash_ocean", "idle")
                tentacle.sg:GoToState("attack_pre")
            end

            Sleep(.5)
        end
    end)

	
		return true
	else
		reader.components.talker:Say("I need grass, reeds or papyrus.")
		return false
	end
end



function onfinished(inst)
    inst:Remove()
end

function MakeBook(name, usefn, bookuses )

    local function fn(Sim)
		local bookname = "book_brimstone"
    	local inst = CreateEntity()
    	local trans = inst.entity:AddTransform()
    	local anim = inst.entity:AddAnimState()
        local sound = inst.entity:AddSoundEmitter()
        anim:SetBank("books")
        anim:SetBuild("books")

        anim:PlayAnimation(bookname)
        MakeInventoryPhysics(inst)
        
        -----------------------------------
        
        inst:AddComponent("inspectable")
        inst:AddComponent("book")
        inst.components.book.onread = usefn

       -- inst:AddComponent("characterspecific")
      --  inst.components.characterspecific:SetOwner("wickerbottom")
        
        inst:AddComponent("inventoryitem")

     --   inst:AddComponent("finiteuses")
     --   inst.components.finiteuses:SetMaxUses( bookuses )
     --   inst.components.finiteuses:SetUses( bookuses )
   --     inst.components.finiteuses:SetOnFinished( onfinished )
   
		local ownertag = "wickerbottom"
		local function undropppable(inst)
					--local found = false
				local owner1 = FindEntity(inst, 1, function(guy) return (guy:HasTag("player3") and guy:HasTag(ownertag) and not guy.components.health:IsDead())end)
				if owner1 then
					local action = ACTIONS.PICKUP 
					local ba = BufferedAction(owner1, inst, action)
					owner1.components.locomotor:PushAction(ba, true)
				end

				
				inst:DoTaskInTime(0.5, function() 
					if inst.components.inventoryitem and inst.components.inventoryitem.owner and inst.components.inventoryitem.owner==nil then
						inst:Remove()
					elseif not owner1 then
						inst:Remove()
					end
				end)
		end
		inst:DoPeriodicTask(10, function()
			inst.components.inventoryitem:ChangeImageName("book_brimstone")

			if inst.components.inventoryitem and inst.components.inventoryitem.owner and inst.components.inventoryitem.owner==GetPlayer() then
				inst:Remove()
			end
		end)
		inst:AddTag("specialitemplayer3")
		inst:ListenForEvent("ondropped", undropppable) 
		inst.components.inventoryitem:ChangeImageName("book_brimstone")
		
		
        MakeSmallBurnable(inst)
        MakeSmallPropagator(inst)


        return inst
    end

    return Prefab( "common/bookplayer3", fn, assets, prefabs) 
end


return MakeBook("bookplayer3", firefn, 5)
