//#target illustrator


/*
  Smart_Pack.jsx for Adobe Illustrator
  Description: Creates artwork from variables.
  Date: September, 2019
  Author: Katja Bjerrum, email: katja@productivista.com , www.productivista.com
  ============================================================================
  NOTICE:
  Tested with Adobe Illustrator CC 2020 (Win), 2019 (Mac).
  This script is provided "as is" without warranty of any kind.
  Free to use, not for sale.
  ============================================================================
  Released under the MIT license.
  http://opensource.org/licenses/mit-license.php
  ============================================================================
  Thanks to: Esben Bjerrum for help with a lot of scripting
  ============================================================================
  Please contact me if you need some help or customization of this script
  at katja@productivista.com
*/


var docRef = app.activeDocument;

var sel = docRef.selection;

app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;

if (docRef.name.match(/Untitled-\d+/gi)) {

    alert("Please save file");
}

else if (sel <= 0) {

    alert("Please make a selection");

}

else {


    var layerCut = layerExists(docRef); 

    var oriGroup = SelectionToNewGroup();

    DuplicateandMove(oriGroup, docRef.dataSets.length);

    DieCuttoNewLayer();//move diecut to new layer

    //fileInfo();

    // Proper way to ungroup groupItems in Illustrator scripting
    for (var i = docRef.groupItems.length - 1; i >= 0; i--) {
        var group = docRef.groupItems[i];
        var parent = group.parent;
        var items = group.pageItems;
        for (var j = items.length - 1; j >= 0; j--) {
            items[j].move(parent, ElementPlacement.PLACEATEND);
        }
        group.remove();
    }
}



function DieCuttoNewLayer() {

    var paths = docRef.pathItems;

    var len = paths.length;

    for (var x = 0; x < len; x++) {

        var ipath = paths[x];

        if (ipath.strokeColor.typename == "SpotColor" && ipath.strokeColor.spot.name == "CutLine" && !ipath.filled) {

            ipath.selected = true;

            // MOVE THE STROKES TO NEW CAD LAYERS

            ipath.moveToBeginning(app.activeDocument.layers["Cuts"]);

            docRef.selection = null;
        }
    }
}


function getDate() {

    var today = new Date();

    var date = "Date created: " + today.getDate() + ' / ' + (today.getMonth() + 1) + ' / ' + today.getFullYear();

    return date;

}

function fileInfo() {

    var pagesnr = docRef.artboards.length; // number of artboards

    for (i = 0; i < pagesnr; i++) // loop thru all artboards

    {
        //Get sizes of the artboard

        var artboard = docRef.artboards[i];

        var aRect = artboard.artboardRect;

        //Save them into separate variables

        var aLeft = aRect[0];

        var aTop = aRect[1];

        var aRight = aRect[2];

        var aBottom = aRect[3];

        var aWidth = aLeft + aRight;

        var fileName = app.activeDocument.textFrames.add();

        fileName.top = aTop - 35;

        fileName.left = aLeft + 50;

        var dot = docRef.name.lastIndexOf('.');

        fileName.contents = app.activeDocument.name.substring(0, dot);//File name;

        var date = app.activeDocument.textFrames.add();

        date.contents = getDate();

        date.top = aTop - 25;

        date.left = aLeft + 50;

        //1 of x pages text

        var pageText = (i + 1) + ' of ' + pagesnr + ' pages ';

        var itext = app.activeDocument.textFrames.add();

        itext.top = aTop - 30;

        itext.left = aRight - 100;

        itext.contents = pageText; //"page 1 of 1";				

    }

}


function SelectionToNewGroup() {

    //Create group from selected items

    if (sel.length > 0) {

        var myGroup = app.activeDocument.groupItems.add();

    }

    for (i = 0; i < sel.length; i++) {

        sel[i].moveToEnd(myGroup);
    }
    myGroup.selected = false;

    return myGroup;
}

function DuplicateandMove(myGroup, j) {

    //coordinates for myGroup

    var width = myGroup.width;

    var left = myGroup.left;

    var top = myGroup.top;

    var height = myGroup.height;

    var right = left + width;

    var bottom = -top + height;

    //Get sizes of the artboard

    var aIndex = docRef.artboards.getActiveArtboardIndex();

    var artboard = docRef.artboards[aIndex];

    var aRect = artboard.artboardRect;

    //Save them into separate variables

    var aLeft = aRect[0];

    var aTop = aRect[1];

    var aRight = aRect[2];

    var aBottom = aRect[3];

    var aWidth = aLeft + aRight;

    //gap

    var newX = width * 0.10;

    var newY = 20;

    //How much to move the item

    var x_Offset = width + newX;

    var y_Offset = - height - newY;

    //counters

    var cc = 0; //column counter;

    var rc = 0; //row counter

    if (right >= (aRect[2] - 10) || bottom >= (-aBottom - 10)) {

        alert('Adjust artboard to your artwork');

        return;
    }

    for (i = 0; i < j; i++) {

        var ds1 = docRef.dataSets[i];

        ds1.display();

        var newGroup = myGroup.duplicate();

        //Calculate right edge of the proposed new item

        var newRight = cc * x_Offset + right;

        if (newRight >= aRect[2] - 20) {

            //Ooops, the object will not fit.
            //Go back to column 1

            cc = 0;

            //Go to next 

            rc = rc + 1;
        }

        //Calculate bottom of the proposed new item

        var newHeight = rc * y_Offset + top - height;

        if (newHeight < aBottom + 10) {

            //Over bottom, make a new artboard

            createNewAB();

            cc = 0;

            rc = 0;
        }
        newGroup.position = [left + cc * x_Offset, top + rc * y_Offset]; //move item

        newGroup.selected = false;

        // Go one position to the right

        var cc = cc + 1;

    }

    myGroup.remove();

}

function getCenter(p) {

    return [p.left + p.width / 2,

    p.top - p.height / 2];

}


//Create new artboard

function createNewAB() {

    var thisBoardIndex = docRef.artboards.getActiveArtboardIndex();

    var thisBoard = docRef.artboards[thisBoardIndex];

    var thisRect = thisBoard.artboardRect;

    var lastBoard = docRef.artboards[docRef.artboards.length - 1];

    var lastRect = lastBoard.artboardRect;

    var newBoard = docRef.artboards.add(thisRect);

    var offsetH = 20;

    newBoard.artboardRect = [

        lastRect[2] + offsetH,

        lastRect[1],

        lastRect[2] + offsetH + (thisRect[2] - thisRect[0]),

        lastRect[3]
    ];  

};

function layerExists(myDoc) {

    //Check if layer "art" exists

    try {

        var myLayer = myDoc.layers.getByName("Cuts");

        myLayer.locked = false;

        myLayer.visible = true;

        return myLayer;

   }

    catch (err) {

        layer = docRef.layers.add();//add new layer
        
         layer.name = "Cuts";
    }
};