--
-- Author: E.T.A La Marchoise
-- Date: 14-07-22
-- Version: 1.0.0.0
-- Copyright (C) E.T.A La Marchoise, All Rights Reserved
-- ExtendedVineCutter.lua
--

ExtendedVineCutter = {};

function ExtendedVineCutter.initSpecialization()
    local schema = Vehicle.xmlSchema;

    schema:setXMLSpecializationType("ExtendedVineCutter");
    schema:register(XMLValueType.STRING, "vehicle.vineCutter#fruitTypes", "Fruit types");
    schema:setXMLSpecializationType();
end

function ExtendedVineCutter.prerequisitesPresent (specializations)
    return SpecializationUtil.hasSpecialization(VineCutter, specializations);
end

function ExtendedVineCutter.registerFunctions(vehicleType)
    SpecializationUtil.registerFunction(vehicleType, "fruitTypeIsValid", ExtendedVineCutter.fruitTypeIsValid);
end


function ExtendedVineCutter.registerOverwrittenFunctions(vehicleType)
    SpecializationUtil.registerOverwrittenFunction(vehicleType, "getIsValidVinePlaceable", ExtendedVineCutter.getIsValidVinePlaceable);
end

function ExtendedVineCutter.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad", ExtendedVineCutter);
end

function ExtendedVineCutter:onLoad(savegame)
    local spec = self.spec_vineCutter;
    local fruitTypes = self.xmlFile:getValue("vehicle.vineCutter#fruitTypes");
    
    if fruitTypes == nil then
        fruitTypes = " ";
    else
        fruitTypes = fruitTypes:split(" ");
    end

    self.vineCutterFruitTypes = {};

    for i, fruitTypeName in pairs(fruitTypes) do
        local fruitType = g_fruitTypeManager:getFruitTypeByName(fruitTypeName);

        if fruitType ~= nil then
            table.insert(self.vineCutterFruitTypes, fruitType.index);
        end
    end
end

function ExtendedVineCutter:getIsValidVinePlaceable(superFunc, placeable)
    if placeable == nil then
        return false;
    end

    local spec = self.spec_vineCutter;
    local vineFruitType = placeable:getVineFruitType();

    if not self:fruitTypeIsValid(vineFruitType) then
        return false;
    end

    spec.inputFruitTypeIndex = vineFruitType;
    spec.outputFillTypeIndex = g_fruitTypeManager:getFillTypeIndexByFruitTypeIndex(spec.inputFruitTypeIndex);

    return true;
end

function ExtendedVineCutter:fruitTypeIsValid(cutterFruitType)
    for _, vineCutterFruitType in pairs(self.vineCutterFruitTypes) do
        if vineCutterFruitType == cutterFruitType then
            return true;
        end
    end

    return false;
end