
local Friends = Class(function(self, inst)
    self.inst = inst

    self.period = 1
    self.friends = {}
    self.friendcheck = {task = nil, flag = {}}

end)

function Friends:OnSave()
    Debug("Save Friends")
    if self.friendcheck.task then self:StopFriendness()
    else self:StartFriendness()
    end
    return {friends = self.friends}
end

function Friends:OnLoad(data)
    Debug("Load friends")
    if data then
        self.friends = data.friends
        Debug("Warmbear has these friends:")
        for k,v in pairs(self.friends) do
            self.friendcheck.flag[k] = false
            Debug({"--", k, ": ", v, "\n"})
        end
    end
    self:StartFriendness()
end

function Friends:StartFriendness()
    if not self.friendcheck.task then
        self.friendcheck.task = self.inst:DoPeriodicTask(self.period,function ()
                self:Check()
            end)
        Debug("Start Friendness caculation")
    end
end

function Friends:StopFriendness()
    if self.friendcheck.task then
        self.friendcheck.task:Cancel()
        self.friendcheck.task = nil
    end
    Debug("Stop Friendness caculation")
end

function Friends:Check()
    local pos = Vector3(self.inst.Transform:GetWorldPosition())
    local ents = TheSim:FindEntities(pos.x,pos.y,pos.z, 20)

    for k,v in pairs(ents) do--对于k来说，v在ents的的范围里，那么
        if v:HasTag("player") and v.name and v.name ~= self.inst.name then
            self.friendcheck.flag[v.name] = true
            self:DoDelta(v.name, 1)
            --self.inst.components.talker:Say(v.name.." nearby.")
        end
    end
    for k,v in pairs(self.friendcheck.flag) do
        if v == false then
            self:DoDelta(k, -0.5)
        else
            self.friendcheck.flag[k] = false
        end
    end
end

function Friends:DoDelta(name, value)
    if not self.friends[name] then
        self.friends[name] = 0
    end
    self.friends[name] = self.friends[name] + value
    if self.friends[name] >= 1200 then 
        self.friends[name] = 1200 
        -- StopFriendness()
    end --prevent friendness above 1000
    if self.friends[name] <= 0 then 
        self.friends[name] = nil 
        -- StopFriendness()
    end --prevent friendness below -1000
end

function Friends:GetDebugString()
    print("Debug Info:\nRuning: ".. tostring(self.friendcheck.task ~= nil) .."\nFriends:")-- body
    for k,v in pairs(self.friends) do
        print("--"..k..":"..v)
    end
end

return Friends