--
-- Multiple prices and farm silos in PDA
--
-- @author  Decker    (ls-uk.info, Decker_MMIV)
-- @date    2011-04-20
--
-- @history
--          v0.9(beta)  Public release, only tested in singleplayer and patch 2.3.

oldMissionPDAdraw = MissionPDA.draw;
MultiplePricesSilosInPda = {};
MultiplePricesSilosInPda.isInitialized = false;

function MultiplePricesSilosInPda:load(xmlFile)
end;
function MultiplePricesSilosInPda:delete()
    MultiplePricesSilosInPda.isInitialized = false;
end;
function MultiplePricesSilosInPda:deleteMap()
    MultiplePricesSilosInPda.isInitialized = false;
end;
function MultiplePricesSilosInPda:mouseEvent(posX, posY, isDown, isUp, button)
end;
function MultiplePricesSilosInPda:keyEvent(unicode, sym, modifier, isDown)
end;

function MultiplePricesSilosInPda:update(dt)
    if (g_currentMission.missionPDA.showPDA) and (g_currentMission.missionPDA.screen == 3) then
        if InputBinding.hasEvent(InputBinding.TOGGLE_PDA_ZOOM) then
            MultiplePricesSilosInPda.fruitOffset = MultiplePricesSilosInPda.fruitOffset + MultiplePricesSilosInPda.fruitsPerPage;
            MultiplePricesSilosInPda.currentFruitSubPage = MultiplePricesSilosInPda.currentFruitSubPage + 1;
            if (MultiplePricesSilosInPda.fruitOffset > table.getn(MultiplePricesSilosInPda.mpSellableFruits)) then
                MultiplePricesSilosInPda.fruitOffset = 1;
                MultiplePricesSilosInPda.stationOffset = MultiplePricesSilosInPda.stationOffset + 3;
                if (MultiplePricesSilosInPda.stationOffset > table.getn(MultiplePricesSilosInPda.mpStations)) then
                    MultiplePricesSilosInPda.stationOffset = 1;
                    MultiplePricesSilosInPda.currentFruitSubPage = 1;
                end;
            end;
            playSample(g_currentMission.missionPDA.pdaBeepSound, 1, 0.5, 0);
        end;
    elseif (g_currentMission.missionPDA.showPDA) and (g_currentMission.missionPDA.screen == 4) then
        if InputBinding.hasEvent(InputBinding.TOGGLE_PDA_ZOOM) then
            MultiplePricesSilosInPda.farmsiloOffset = MultiplePricesSilosInPda.farmsiloOffset + MultiplePricesSilosInPda.farmsilosPerPage;
            MultiplePricesSilosInPda.currentFarmsiloSubPage = MultiplePricesSilosInPda.currentFarmsiloSubPage + 1;
            if (MultiplePricesSilosInPda.farmsiloOffset > table.getn(MultiplePricesSilosInPda.mpFarmSiloFillTypes)) then
                MultiplePricesSilosInPda.farmsiloOffset = 1;
                MultiplePricesSilosInPda.currentFarmsiloSubPage = 1;
            end;
            playSample(g_currentMission.missionPDA.pdaBeepSound, 1, 0.5, 0);
        end;
    end;
end;

function MultiplePricesSilosInPda:draw()
end;

function MultiplePricesSilosInPda:loadMap(name)
    if MultiplePricesSilosInPda.isInitialized then
        -- Already initialized.
        return;
    end;
    -- Initialise because global objects do not get cleared between map-loads.
    MultiplePricesSilosInPda.mpStations = {};
    MultiplePricesSilosInPda.mpSellableFruits = {};
    MultiplePricesSilosInPda.stationOffset = 1;
    MultiplePricesSilosInPda.fruitOffset = 1;
    MultiplePricesSilosInPda.currentFruitSubPage = 1;
    MultiplePricesSilosInPda.numOfFruitSubPages = 0;
    MultiplePricesSilosInPda.fruitsPerPage = 10;
    --
    MultiplePricesSilosInPda.mpFarmSiloFillTypes = {};
    MultiplePricesSilosInPda.farmsiloOffset = 1;
    MultiplePricesSilosInPda.currentFarmsiloSubPage = 1;
    MultiplePricesSilosInPda.numOfFarmsiloSubPages = 0;
    MultiplePricesSilosInPda.farmsilosPerPage = 10;

    -- Determine what stations there are and what they accept. Also figure out what farm-triggers(silos) are available.
    local stations = {};
    local sellable = {};
    local farmsilo = {};
    for k,tipTrig in pairs(g_currentMission.tipTriggers) do
        if (tipTrig.appearsOnPDA) and (stations[tipTrig.stationName] ~= true) then   -- Make sure we do not include the same stationName again.
            for fruitIndex=1, FruitUtil.NUM_FRUITTYPES do
                if (tipTrig.acceptedFruitTypes[fruitIndex]) then
                    sellable[fruitIndex] = true;
                end;
            end;
            stations[tipTrig.stationName] = true;
            table.insert(MultiplePricesSilosInPda.mpStations, tipTrig);
        end;
        if (tipTrig.isFarmTrigger) then
            for fruitIndex=1, FruitUtil.NUM_FRUITTYPES do
                if (tipTrig.acceptedFruitTypes[fruitIndex]) then
                    farmsilo[fruitIndex] = true;
                end;
            end;
        end;
    end;
    -- Maybe not optimal sort-code, with all the g_i18n-calls, but this table.sort() probably is only called once when map is loaded.
    table.sort(MultiplePricesSilosInPda.mpStations, function(l,r)
        local lName = l.stationName;
        local rName = r.stationName;
        if (g_i18n:hasText(lName)) then lName = g_i18n:getText(lName); end;
        if (g_i18n:hasText(rName)) then rName = g_i18n:getText(rName); end;
        return (lName < rName);  -- TODO, need localization-comparsion.
        end
    );
    -- Only sellable types should be shown in the PDA, so we do not get any "blank lines".
    for fruitIndex,isSellable in pairs(sellable) do
        if isSellable then
            table.insert(MultiplePricesSilosInPda.mpSellableFruits, fruitIndex);
        end;
    end;
    --
    MultiplePricesSilosInPda.numOfFruitSubPages = math.ceil(table.getn(MultiplePricesSilosInPda.mpSellableFruits) / MultiplePricesSilosInPda.fruitsPerPage) * math.ceil(table.getn(MultiplePricesSilosInPda.mpStations) / 3);
    --
    for fruitIndex,hasFarmSilo in pairs(farmsilo) do
        if hasFarmSilo then
            if (    fruitIndex ~= FruitUtil.FRUITTYPE_GRASS
                and fruitIndex ~= FruitUtil.FRUITTYPE_DRYGRASS
                and fruitIndex ~= FruitUtil.FRUITTYPE_CHAFF) then
                table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, FruitUtil.fruitTypeToFillType[fruitIndex]);
            end;
        end;
    end;
    -- Add additional "fillTypes" that (may) have no corresponding "fruitType".
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, -1); -- Magic-number for Cows
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_LIQUIDMANURE);
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_MANURE);
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_CHAFF);
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_GRASS);
    table.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_MILK);
    --ble.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_FERTILIZER);
    --ble.insert(MultiplePricesSilosInPda.mpFarmSiloFillTypes, Fillable.FILLTYPE_SEEDS);
    --
    MultiplePricesSilosInPda.numOfFarmsiloSubPages = math.ceil(table.getn(MultiplePricesSilosInPda.mpFarmSiloFillTypes) / MultiplePricesSilosInPda.farmsilosPerPage);
    --

--
--  print("Stations:");
--  for k,v in pairs(MultiplePricesSilosInPda.mpStations) do
--      print(string.format("%d %s", k, v.stationName));
--  end;
--  print("Sellable fruits:");
--  for k,v in pairs(MultiplePricesSilosInPda.mpSellableFruits) do
--      print(string.format("%d %s", k, FruitUtil.fruitIndexToDesc[v].name));
--  end;
--  print("FarmSilo fillables:");
--  for k,v in pairs(MultiplePricesSilosInPda.mpFarmSiloFillTypes) do
--      if (v > 0) then
--          print(string.format("%d %s", k, Fillable.fillTypeIntToName[v]));
--      end;
--  end;

    MultiplePricesSilosInPda.isInitialized = true;
end;


--
-- Overload the MissionPDA.draw function, so we can control screen 3 and 4.
--
MissionPDA.draw = function(self)
    if (oldMissionPDAdraw ~= nil) and (g_currentMission.missionPDA.screen ~= 3 and g_currentMission.missionPDA.screen ~= 4) then
        oldMissionPDAdraw(self)
    elseif (g_currentMission.missionPDA.showPDA) and (g_currentMission.missionPDA.screen == 3) then
        -- First render the background
        g_currentMission.missionPDA.hudPDABackgroundOverlay:render();

        -- Draw the stations
        setTextColor(0.85, 0.85, 1.0, 1.0);
        setTextAlignment(RenderText.ALIGN_LEFT);
        local y = g_currentMission.missionPDA.pdaTitleY - g_currentMission.missionPDA.pdaRowSpacing;
        setTextBold(true);
        local xCol=2;
        for j=MultiplePricesSilosInPda.stationOffset, math.min(MultiplePricesSilosInPda.stationOffset+2, table.getn(MultiplePricesSilosInPda.mpStations)) do
            local stationName = MultiplePricesSilosInPda.mpStations[j].stationName;
            if g_i18n:hasText(stationName) then
                stationName = g_i18n:getText(stationName);
            end;
            renderText(
                g_currentMission.missionPDA.pdaPricesCol[xCol],
                y,
                g_currentMission.missionPDA.pdaFontSize,
                stationName
            );
            xCol = xCol + 1;
        end;
        y = y - g_currentMission.missionPDA.pdaRowSpacing;

        -- Draw the fruits and their prices for the stations
        local factor = 6000;
        if g_currentMission.missionStats.difficulty>=3 then
            factor = 1000;
        elseif g_currentMission.missionStats.difficulty>=2 then
            factor = 3000;
        end;
        local pricePerTon = g_i18n:getText("PricePerTon");
        setTextBold(false);
        for i=MultiplePricesSilosInPda.fruitOffset, math.min(MultiplePricesSilosInPda.fruitOffset+(MultiplePricesSilosInPda.fruitsPerPage-1), table.getn(MultiplePricesSilosInPda.mpSellableFruits)) do
            local fruitIndex = MultiplePricesSilosInPda.mpSellableFruits[i];
            local fruitName = FruitUtil.fruitIndexToDesc[fruitIndex].name;
            if g_i18n:hasText(fruitName) then
                fruitName = g_i18n:getText(fruitName);
            end;
            fruitName = fruitName.." "..pricePerTon;
            setTextAlignment(RenderText.ALIGN_LEFT);
            setTextColor(0.85, 0.85, 1.0, 1.0);
            renderText(
                g_currentMission.missionPDA.pdaPricesCol[1],
                y,
                g_currentMission.missionPDA.pdaFontSize,
                fruitName
            );
            xCol=2;
            setTextAlignment(RenderText.ALIGN_RIGHT);
            for j=MultiplePricesSilosInPda.stationOffset, math.min(MultiplePricesSilosInPda.stationOffset+2, table.getn(MultiplePricesSilosInPda.mpStations)) do
                if MultiplePricesSilosInPda.mpStations[j].acceptedFruitTypes[fruitIndex] then
                    local price = FruitUtil.fruitIndexToDesc[fruitIndex].pricePerLiter;
                    if (price < FruitUtil.fruitIndexToDesc[fruitIndex].yesterdaysPrice) then
                        setTextColor(1.0, 0.2, 0.2, 1.0);   -- Red'ish
                    elseif (price > FruitUtil.fruitIndexToDesc[fruitIndex].yesterdaysPrice) then
                        setTextColor(0.2, 1.0, 0.2, 1.0);   -- Green'ish
                    else
                        setTextColor(0.85, 0.85, 1.0, 1.0); -- Whiteblue'ish
                    end;
                    price = math.floor(price * factor * MultiplePricesSilosInPda.mpStations[j].priceMultipliers[fruitIndex]);
                    renderText(
                        g_currentMission.missionPDA.pdaPricesCol[xCol] + 0.05,
                        y,
                        g_currentMission.missionPDA.pdaFontSize,
                        string.format("%d", price)
                    );
                end;
                xCol = xCol + 1;
            end;
            y = y - g_currentMission.missionPDA.pdaRowSpacing;
        end;

        -- Draw page#-of-pages
        setTextAlignment(RenderText.ALIGN_LEFT);
        setTextColor(0.85, 0.85, 1.0, 0.8);
        renderText(
            g_currentMission.missionPDA.pdaPricesCol[5] + 0.005,
            g_currentMission.missionPDA.hudPDABasePosY + g_currentMission.missionPDA.pdaTopSpacing + g_currentMission.missionPDA.pdaFontSize,
            g_currentMission.missionPDA.pdaFontSize - 0.002,
            string.format("%d/%d", MultiplePricesSilosInPda.currentFruitSubPage, MultiplePricesSilosInPda.numOfFruitSubPages)
        );

        -- Render the frame
        g_currentMission.missionPDA.hudPDAFrameOverlay:render();

        -- Draw screen-title (with black shadow)
        setTextBold(true);
        setTextColor(0,0,0, 1); -- Black
        renderText(
            g_currentMission.missionPDA.pdaTitleX - 0.001,
            g_currentMission.missionPDA.pdaTitleY - 0.002,
            g_currentMission.missionPDA.pdaTitleTextSize,
            g_currentMission.missionPDA.textTitles[3]
        );
        setTextColor(1,1,1, 1); -- White
        renderText(
            g_currentMission.missionPDA.pdaTitleX,
            g_currentMission.missionPDA.pdaTitleY,
            g_currentMission.missionPDA.pdaTitleTextSize,
            g_currentMission.missionPDA.textTitles[3]
        );
    elseif (g_currentMission.missionPDA.showPDA) and (g_currentMission.missionPDA.screen == 4) then
        -- First render the background
        g_currentMission.missionPDA.hudPDABackgroundOverlay:render();

        -- Draw the farm silos
        setTextColor(0.8, 0.9, 1.0, 1.0);
        setTextAlignment(RenderText.ALIGN_LEFT);
        setTextBold(false);
        local y = g_currentMission.missionPDA.pdaTitleY - (g_currentMission.missionPDA.pdaRowSpacing * 1.5);
        local storageSuf = "storage";
        if g_i18n:hasText(storageSuf) then
            storageSuf = g_i18n:getText(storageSuf);
        end;
        for i=MultiplePricesSilosInPda.farmsiloOffset, math.min(MultiplePricesSilosInPda.farmsiloOffset+(MultiplePricesSilosInPda.farmsilosPerPage-1), table.getn(MultiplePricesSilosInPda.mpFarmSiloFillTypes)) do
            local fillIndex = MultiplePricesSilosInPda.mpFarmSiloFillTypes[i];
            local fillName;
            local fillAmount;
            local suffix = "";
            if fillIndex == -1 then     -- Magic-number
                fillName = "Cows_owned";
                fillAmount = Utils.getNoNil(AnimalHusbandry.getNumberOfAnimals(), 0);
            else
                suffix = " ["..g_i18n:getText("fluid_unit_short").."]";
                if     (fillIndex == Fillable.FILLTYPE_BARLEY)          then  fillName = "Barley_storage";
                elseif (fillIndex == Fillable.FILLTYPE_WHEAT)           then  fillName = "Wheat_storage";
                elseif (fillIndex == Fillable.FILLTYPE_RAPE)            then  fillName = "Rapeseed_storage";
                elseif (fillIndex == Fillable.FILLTYPE_MAIZE)           then  fillName = "Maize_storage";
                elseif (fillIndex == Fillable.FILLTYPE_LIQUIDMANURE)    then  fillName = "LiquidManure_storage";
                elseif (fillIndex == Fillable.FILLTYPE_MANURE)          then  fillName = "Manure_storage";
                elseif (fillIndex == Fillable.FILLTYPE_CHAFF)           then  fillName = "MaizeSilage_storage";
                elseif (fillIndex == Fillable.FILLTYPE_GRASS)           then  fillName = "GrassSilage_storage";
                elseif (fillIndex == Fillable.FILLTYPE_MILK)            then  fillName = "Milk_storage";
                else
                    fillName = Fillable.fillTypeIntToName[fillIndex];
                    suffix = " "..storageSuf..suffix;
                end;
                fillAmount = Utils.getNoNil(g_currentMission.missionStats.farmSiloAmounts[fillIndex],0);
                if (fillIndex == Fillable.FILLTYPE_GRASS) then
                    fillAmount = fillAmount + Utils.getNoNil(g_currentMission.missionStats.farmSiloAmounts[Fillable.FILLTYPE_DRYGRASS],0);
                end;
                fillAmount = math.floor(fillAmount);
            end;
            if g_i18n:hasText(fillName) then
                fillName = g_i18n:getText(fillName);
            end;
            fillName = fillName..suffix;

            renderText(
                g_currentMission.missionPDA.pdaUserCol[1],
                y,
                g_currentMission.missionPDA.pdaFontSize,
                fillName
            );
            renderText(
                g_currentMission.missionPDA.pdaUserCol[2],
                y,
                g_currentMission.missionPDA.pdaFontSize,
                tostring(fillAmount)
            );

            y = y - g_currentMission.missionPDA.pdaRowSpacing;
        end;

        -- Draw page#-of-pages
        setTextAlignment(RenderText.ALIGN_LEFT);
        setTextColor(0.85, 0.85, 1.0, 0.8);
        renderText(
            g_currentMission.missionPDA.pdaPricesCol[5] + 0.005,
            g_currentMission.missionPDA.hudPDABasePosY + g_currentMission.missionPDA.pdaTopSpacing + g_currentMission.missionPDA.pdaFontSize,
            g_currentMission.missionPDA.pdaFontSize - 0.002,
            string.format("%d/%d", MultiplePricesSilosInPda.currentFarmsiloSubPage, MultiplePricesSilosInPda.numOfFarmsiloSubPages)
        );

        -- Render the frame
        g_currentMission.missionPDA.hudPDAFrameOverlay:render();

        -- Draw screen-title (with black shadow)
        setTextBold(true);
        setTextColor(0,0,0, 1); -- Black
        renderText(
            g_currentMission.missionPDA.pdaTitleX - 0.001,
            g_currentMission.missionPDA.pdaTitleY - 0.002,
            g_currentMission.missionPDA.pdaTitleTextSize,
            g_currentMission.missionPDA.textTitles[4]
        );
        setTextColor(1,1,1, 1); -- White
        renderText(
            g_currentMission.missionPDA.pdaTitleX,
            g_currentMission.missionPDA.pdaTitleY,
            g_currentMission.missionPDA.pdaTitleTextSize,
            g_currentMission.missionPDA.textTitles[4]
        );
    end;
end;

addModEventListener(MultiplePricesSilosInPda);
print(" --Mini_Mini_Map Script loaded: MultiplePricesSilosInPda.lua");
