-- PriceMod by Hewaaa
oldMissionPDAdraw = MissionPDA.draw;


PriceMod = {};
PriceMod.isInitialized = false;


function PriceMod:load(xmlFile)
end;

function PriceMod:delete()
    PriceMod.isInitialized = false;
end;

function PriceMod:deleteMap()
    PriceMod.isInitialized = false;
end;

function PriceMod:mouseEvent(posX, posY, isDown, isUp, button)
end;

function PriceMod:keyEvent(unicode, sym, modifier, isDown)
end;

function PriceMod:update(dt)
    if (g_currentMission.missionPDA.showPDA) and (g_currentMission.missionPDA.screen == 3) then
        if InputBinding.hasEvent(InputBinding.TOGGLE_PDA_ZOOM) then
            PriceMod.fruitOffset = PriceMod.fruitOffset + PriceMod.fruitsPerPage;
            PriceMod.currentFruitSubPage = PriceMod.currentFruitSubPage + 1;
            if (PriceMod.fruitOffset > table.getn(PriceMod.mpSellableFruits)) then
                PriceMod.fruitOffset = 1;
                PriceMod.stationOffset = PriceMod.stationOffset + 3;
                if (PriceMod.stationOffset > table.getn(PriceMod.mpStations)) then
                    PriceMod.stationOffset = 1;
                    PriceMod.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
            PriceMod.farmsiloOffset = PriceMod.farmsiloOffset + PriceMod.farmsilosPerPage;
            PriceMod.currentFarmsiloSubPage = PriceMod.currentFarmsiloSubPage + 1;
            if (PriceMod.farmsiloOffset > table.getn(PriceMod.mpFarmSiloFillTypes)) then
                PriceMod.farmsiloOffset = 1;
                PriceMod.currentFarmsiloSubPage = 1;
            end;
            playSample(g_currentMission.missionPDA.pdaBeepSound, 1, 0.5, 0);
        end;
    end;
end;

function PriceMod:draw()
end;

function PriceMod:loadMap(name)
    if PriceMod.isInitialized then
        -- Already initialized.
        return;
    end;

    -- Initialise because global objects do not get cleared between map-loads.
    PriceMod.mpStations = {};
    PriceMod.mpSellableFruits = {};
    PriceMod.stationOffset = 1;
    PriceMod.fruitOffset = 1;
    PriceMod.currentFruitSubPage = 1;
    PriceMod.numOfFruitSubPages = 0;
    PriceMod.fruitsPerPage = 10;
    --
    PriceMod.mpFarmSiloFillTypes = {};
    PriceMod.farmsiloOffset = 1;
    PriceMod.currentFarmsiloSubPage = 1;
    PriceMod.numOfFarmsiloSubPages = 0;
    PriceMod.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(PriceMod.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(PriceMod.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(PriceMod.mpSellableFruits, fruitIndex);
        end;
    end;
    --
    PriceMod.numOfFruitSubPages = math.ceil(table.getn(PriceMod.mpSellableFruits) / PriceMod.fruitsPerPage) * math.ceil(table.getn(PriceMod.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(PriceMod.mpFarmSiloFillTypes, FruitUtil.fruitTypeToFillType[fruitIndex]);
            end;
        end;
    end;
    -- Add additional "fillTypes" that (may) have no corresponding "fruitType".
    table.insert(PriceMod.mpFarmSiloFillTypes, -1); -- Magic-number for Cows
    table.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_LIQUIDMANURE);
    table.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_MANURE);
    table.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_CHAFF);
    table.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_GRASS);
    table.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_MILK);
    --ble.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_FERTILIZER);
    --ble.insert(PriceMod.mpFarmSiloFillTypes, Fillable.FILLTYPE_SEEDS);
    --
    PriceMod.numOfFarmsiloSubPages = math.ceil(table.getn(PriceMod.mpFarmSiloFillTypes) / PriceMod.farmsilosPerPage);
    --

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

    PriceMod.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=PriceMod.stationOffset, math.min(PriceMod.stationOffset+2, table.getn(PriceMod.mpStations)) do
            local stationName = PriceMod.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=PriceMod.fruitOffset, math.min(PriceMod.fruitOffset+(PriceMod.fruitsPerPage-1), table.getn(PriceMod.mpSellableFruits)) do
            local fruitIndex = PriceMod.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=PriceMod.stationOffset, math.min(PriceMod.stationOffset+2, table.getn(PriceMod.mpStations)) do
                if PriceMod.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 * PriceMod.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", PriceMod.currentFruitSubPage, PriceMod.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=PriceMod.farmsiloOffset, math.min(PriceMod.farmsiloOffset+(PriceMod.farmsilosPerPage-1), table.getn(PriceMod.mpFarmSiloFillTypes)) do
            local fillIndex = PriceMod.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";
                elseif (fillIndex == Fillable.FILLTYPE_DEUKA)           then  fillName = "Mischkraftfutter";
                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", PriceMod.currentFarmsiloSubPage, PriceMod.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(PriceMod);
print("Script loaded: PriceMod.lua");
