-- ptoBrake by s8080t <s8080t@sevenlayers.org>
-- Do not publish/recycle without my written consent.
-- v1.0.0.0

ptoBrake = {};
ptoBrake.modName = g_currentModName;
ptoBrake.attribute = "g_currentMission.controlledVehicle.spec_motorized.motor.lowBrakeForceScale"
ptoBrake.valueOn = 0.8

function ptoBrake.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(TurnOnVehicle, specializations)
end

function ptoBrake.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onTurnedOn", ptoBrake)
    SpecializationUtil.registerEventListener(vehicleType, "onTurnedOff", ptoBrake)
end

function ptoBrake:setValue(str, arg1)
    if not ptoBrake:isEmpty(str) and not ptoBrake:isEmpty(arg1) then
        ptoBrake.valueOff = ptoBrake:stringToTable(str);
        t = getfenv(0);
        for w, d in string.gfind(str, "([%w_]+)(.?)") do
            if d == "." then
              t = t[w];
            else	  
                if tonumber(arg1) ~= nil then
                    t[w] = tonumber(arg1);
                else
                    t[w] = arg1;
                end;
            end;
        end;
    elseif not ptoBrake:isEmpty(str) then
        print("Value: "..ptoBrake:stringToTable(str));
    else
        print ("ptoBrake: setting new value failed");
    end
end

function ptoBrake:stringToTable(str)
    local levels = StringUtil.splitString(".", str);
    local levelsDepth = table.getn(levels);
    local tmpTable = getfenv(0);
    local result;
    if levels ~= nil and levelsDepth > 0 then
        for k,v in pairs(levels) do
            if tonumber(v) ~= nil then
                tmpTable = tmpTable[tonumber(v)];
            else
                tmpTable = tmpTable[tostring(v)];
            end;
        end;
        result = tmpTable;
    else
        print("ptoBrake: creating table failed");
    end;
    return result;
end;

function ptoBrake:isEmpty(s)
  return s == nil or s == '';
end

function ptoBrake:onTurnedOn()
    ptoBrake:setValue(ptoBrake.attribute, ptoBrake.valueOn)
end

function ptoBrake:onTurnedOff()
    ptoBrake:setValue(ptoBrake.attribute, ptoBrake.valueOff)
end

print("ptoBrake loaded.")
