--
-- Author: E.T.A La Marchoise & Matteo7810
-- Date: 15-07-22
-- Version: 1.0.0.0
-- Copyright (C) E.T.A La Marchoise, All Rights Reserved
-- ExtendedVinePrepruner.lua
--

ExtendedVinePrepruner = {}

function ExtendedVinePrepruner.initSpecialization()
    local schema = Vehicle.xmlSchema

    schema:setXMLSpecializationType("ExtendedVinePrepruner")
    schema:register(XMLValueType.STRING, "vehicle.vinePrepruner#fruitTypes", "Fruit types")
    schema:setXMLSpecializationType()
end

function ExtendedVinePrepruner.prerequisitesPresent (specializations)
    return SpecializationUtil.hasSpecialization(VinePrepruner, specializations)
end

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


function ExtendedVinePrepruner.registerOverwrittenFunctions(vehicleType)
    SpecializationUtil.registerOverwrittenFunction(vehicleType, "handleVinePlaceable", ExtendedVinePrepruner.handleVinePlaceable)
    SpecializationUtil.registerOverwrittenFunction(vehicleType, "getIsValidVinePlaceable", ExtendedVinePrepruner.getIsValidVinePlaceable)
end

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

function ExtendedVinePrepruner:onLoad(savegame)
    local spec = self.spec_vinePrepruner
    local fruitTypes = self.xmlFile:getValue("vehicle.vinePrepruner#fruitTypes")
    
    if fruitTypes == nil then
        fruitTypes = "GRAPE"
    else
        fruitTypes = fruitTypes:split(" ")
    end

    self.vinePreprunerFruitTypes = {}

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

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

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

    local spec = self.spec_vinePrepruner
    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 ExtendedVinePrepruner:handleVinePlaceable(superFunc, node, placeable, x, y, z, distance)

	if not superFunc(self, node, placeable, x, y, z, distance) then
		return false
	end
	
	placeable:updateVineNode(node, false)
	
	return oldRetVal
end

function ExtendedVinePrepruner:fruitTypeIsValid(preprunerFruitType)
    for _, vinePreprunerFruitType in pairs(self.vinePreprunerFruitTypes) do
        if vinePreprunerFruitType == preprunerFruitType then
            return true
        end
    end

    return false
end