-- FishingPlans
--
-- Let's make a plan that we can carry through with, allowing us to group
-- item choices instead of handling each item separately.

-- 5.0.4 has a problem with a global "_" (see some for loops below)
local _

local FL = LibStub("LibFishing-1.0");

local GSB = FishingBuddy.GetSettingBool
local CurLoc = GetLocale();

local function HaveThing(itemid, info)
    if (info.toy) then
        return PlayerHasToy(itemid)
    else
        return GetItemCount(itemid) > 0;
    end
end
FishingBuddy.HaveThing = HaveThing

local function ItemCooldownOn(id)
    local start, duration, enable = GetItemCooldown(id);
    local et = (start + duration) - GetTime();
    if (et > 0) then
        return true;
    end
    -- return false
end
FishingBuddy.ItemCooldownOn = ItemCooldownOn

local function AlreadyUsedFishingItem(id, info)
    if (info.spell) then
        return FL:HasBuff(info.spell);
    end
end

local function CanUseFishingItem(id, info)
    if not info.setting or GSB(info.setting) then
        if HaveThing(id, info) and (not info.usable or info.usable(info) ) then
            if (not info[CurLoc]) then
                info[CurLoc] = GetItemInfo(id);
            end
            if not (AlreadyUsedFishingItem(id, info) or ItemCooldownOn(id, info)) then
                return true;
            end
        end
    end
    return false;
end
FishingBuddy.CanUseFishingItem = CanUseFishingItem

local function CanUseFishingItems(items)
    for id, info in pairs(items) do
        if CanUseFishingItem(id, info) then
            return true, id, info.curLoc, nil;
        end
    end
    return false;
end
FishingBuddy.CanUseFishingItems = CanUseFishingItems

local planners = {}
local function RegisterPlan(planner)
    tinsert(planners, planner)
end
FishingBuddy.RegisterPlan = RegisterPlan

local planqueue = {}
local function HavePlans()
    return #planqueue > 0
end
FishingBuddy.HavePlans = HavePlans

local function GetPlan()
    if HavePlans() then
        local head = table.remove(planqueue, 1)
        return true, head.itemid, head.name, head.targetid
    end
    -- return nil
end
FishingBuddy.GetPlan = GetPlan

local function ExecutePlans(force)
    if (force or not HavePlans()) then
        planqueue = {}
        for _,planner in ipairs(planners) do
            planner(planqueue)
        end
    end
end
FishingBuddy.ExecutePlans = ExecutePlans

local PlanEvents = {}
PlanEvents[FBConstants.FISHING_DISABLED_EVT] = function()
    planqueue = {}
end

FishingBuddy.RegisterHandlers(PlanEvents);

if ( FishingBuddy.Debugging ) then
	FishingBuddy.Commands["plans"] = {};
	FishingBuddy.Commands["plans"].func =
        function(what)
            ExecutePlans(what);
            FishingBuddy.Dump(planqueue)
			return true;
		end
end
