//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// iRacing paint exporter
//
// Created by Samuel Cordingly. (https://members.iracing.com/jforum/posts/list/3795673.page)
//
// Modified by Ash Kendall. ash.kendall(at)gmail.com
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTES:
// - Customer ID must be updated below!
// - PSD start with the correct name for the car, based on the paint folder name
// -- e.g. Porsche 911 GT3 Cup (991) should be named 'porsche911cup.psd'
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

<javascriptresource>
    <name>$$$/Menu=Export to iRacing</name>
    <category>Scripts</category>
</javascriptresource>

#target photoshop

// Get iRacing paint path
homeDrive = $.getenv("HOMEDRIVE");
homePath = $.getenv("HOMEPATH");
paintPath = homeDrive + homePath + "\\Documents\\iRacing\\paint";

doc = app.activeDocument;

// Customer ID!!
custID = "135364";

// Get car info from filename
carModel = doc.name.split(".")[0];
carPath = paintPath + "\\" + carModel;

// Original version...
// Get car and customer ID from filename
//carInfo = doc.name.split(".")[0].split("_")
//carModel = carInfo[0];
//carPath = paintPath + "\\" + carModel;
//carNum = carInfo[carInfo.length - 1];

// Get layers
specLayer = doc.layers["Custom Spec Map"];
albedoLayer = doc.layers["Paintable Area"];
infoLayer = doc.layers["Turn Off Before Exporting TGA"];

// store visibility of layers so that we can go back to how they were
specVisible = specLayer.visible;
albedoVisible = albedoLayer.visible;
infoVisible = infoLayer.visible;

// save spec layer
specPath = carPath + "\\car_spec_" + custID;
albedoLayer.visible = false;
infoLayer.visible = false;
specLayer.visible = true;
saveTarga(specPath);

// save main paint layer
albedoPath = carPath + "\\car_" + custID;
albedoLayer.visible = true;
infoLayer.visible = false;
specLayer.visible = false;
saveTarga(albedoPath);

// undo visibility changes
albedoLayer.visible = albedoVisible;
specLayer.visible = specVisible;
infoLayer.visible = infoVisible;

function saveTarga(filepath)
{
    targaSaveOptions = new TargaSaveOptions();
    targaSaveOptions.alphaChannels = true;
    targaSaveOptions.resolution = TargaBitsPerPixels.THIRTYTWO;
    app.activeDocument.saveAs(File(filepath), targaSaveOptions, true, Extension.LOWERCASE);
};