//Script for UPDM 2019 Data Models
//Script to decode and populate the MANUFACTUREDATE value from the BARCODE value

var barcode = $feature.BARCODE;
if (barcode == null)   // Preserve original MANUFACTUREDATE value if BARCODE is null
  return $feature.MANUFACTUREDATE;

var input = mid(barcode,6,3);
var BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

var digit;
var x = 0;
for (digit=1; digit <= count(input); digit++) 
        x = x * count(BASE62) + find(mid(input,digit-1,1),BASE62,0); 

var inputdays;
var inputyear;
var inputdate;
var returndate;

if (x > 99999) // 6 digit value
{   
   inputdays = Number(mid(x,0,4));
   inputyear = Number(mid(x,4,2));
}

if (x > 9999 && x <=99999)   //5 digit value
{
   inputdays = Number(mid(x,0,3));
   inputyear = Number(mid(x,3,2));
}

if (x > 999 && x <=9999)   // 4 digit value
{
   inputdays = Number(mid(x,0,2));
   inputyear = Number(mid(x,2,2));
}

if (x > 99 && x <=999)   // 3 digit value
{
   inputdays = mid(x,0,1);
   inputyear = mid(x,1,2);
}

returndate = DateAdd(2000 + inputyear + '-01-01', inputdays -1, 'days');
if (returndate > Now())
    returndate = DateAdd(Year(Now()) + '-01-01', 0, 'days');

return text(returndate, 'M/DD/YY');