--[[
BY
 _____   _____   __   _  
|  _  \ /  _  \ |  \ | | 
| | | | | | | | |   \| | 
| | | | | | | | | |\   | 
| |_| | | |_| | | | \  | 
|_____/ \_____/ |_|  \_| 

]]

local assets =
{
    Asset("ANIM", "anim/donphonograph.zip"),
}

local prefabs =
{

}

local function turnon(inst)
	inst.components.machine.ison = true
	
	inst.AnimState:PlayAnimation("play_loop", true)
	inst.SoundEmitter:KillSound("donphonographmusic")
    inst.SoundEmitter:PlaySound("dontstarve/music/gramaphone_start")
	
    inst.SoundEmitter:PlaySound("dontstarve/maxwell/ragtime", "donphonographmusic")
	inst.SoundEmitter:SetVolume("donphonographmusic", 0.3)
end

local function turnoff(inst)
	inst.components.machine.ison = false
	
	inst.AnimState:PlayAnimation("idle", true)
    inst.SoundEmitter:KillSound("donphonographmusic")
    inst.SoundEmitter:PlaySound("dontstarve/music/gramaphone_end")
end

local function OnDropped(inst)
	turnoff(inst)
end

local function OnPutInInventory(inst)
	turnoff(inst)
end

local function onload(inst, data)
	if inst.components.machine.ison == true then
		turnon(inst)
	else
		turnoff(inst)
	end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddLight()
    inst.entity:AddNetwork()

    MakeInventoryPhysics(inst)

	MakeObstaclePhysics(inst, 0.14)
	
    inst.AnimState:SetBank("donphonograph")
    inst.AnimState:SetBuild("donphonograph")
    inst.AnimState:PlayAnimation("idle", true)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("inspectable")
    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem.nobounce = true

    inst:AddComponent("lootdropper")
	
	inst:AddComponent("machine")
	inst.components.machine.turnonfn = turnon
	inst.components.machine.turnofffn = turnoff
	inst.components.machine.ison = false
	
	inst:AddComponent("playerprox")
	inst.components.playerprox:SetDist(25, 28)
	inst.components.playerprox:SetOnPlayerFar(turnoff)
	
    inst.components.inventoryitem:SetOnDroppedFn(OnDropped)
    inst.components.inventoryitem:SetOnPutInInventoryFn(OnPutInInventory)
	inst.components.inventoryitem.imagename = ("donphonographicon")
	inst.components.inventoryitem.atlasname = ("images/inventoryimages/donphonographicon.xml")

    inst.OnLoad = onload

    return inst
end

return Prefab("donphonograph", fn, assets, prefabs)
