/**
 * returns an array of RecType Structures for all RecTypes
 * rectypes = {{"groups":{"groupIDToIndex":{recTypeGroupID:index},
 *                         recTypeGroupID:{propName:val,...},...}},
 *             "names":{rtyID:name,...},
 *             "pluralNames":{rtyID:pluralName,...},
 *             "usageCount":{rtyID:nonzero-count,...},
 *             "dtDisplayOrder":{rtyID:[ordered dtyIDs], ...},
 *             "typedefs":{"commonFieldNames":[defRecType Column names],
 *                         "commonNamesToIndex":{"defRecTypes columnName":index,...},
 *                         "dtFieldNamesToIndex":{"defRecStructure columnName":index,...},
 *                         "dtFieldNames":[defRecStructure Column names],
 *                         rtyID:{"dtFields":{dtyID:[val,...]},
 *                                 "commonFields":[val,....]},
 *                         ...},
 *             "constraints":[]}};
 *
 * @global    int $dbID databse ID
 * @param     boolean $useCachedData if true does a lookup for the rectypes structure in cache
 * @return    object iformation describing all the rectypes defined in the database
 * @uses      getRectypeColNames()
 * @uses      getColumnNameToIndex()
 * @uses      getRectypeStructureFieldColNames()
 * @uses      DATABASE
 * @uses      getCachedData()
 * @uses      setCachedData()
 * @uses      getRectypeGroups()
 * @uses      getRecTypeUsageCount()
 */
function getAllRectypeStructures($useCachedData = false)
{
    global $dbID;
    $cacheKey = DATABASE . ":AllRecTypeInfo";
    if ($useCachedData) {
        $rtStructs = getCachedData($cacheKey);
        if ($rtStructs) {
            return $rtStructs;
        }
    }
    // NOTE: these are ordered to match the order of getRectypeStructureFieldColNames from DisplayName on
    $colNames = array("rst_RecTypeID", "rst_DetailTypeID", "if(rst_DisplayName is not null and CHAR_LENGTH(rst_DisplayName)>0,rst_DisplayName,dty_Name) as rst_DisplayName", "if(rst_DisplayHelpText is not null and CHAR_LENGTH(rst_DisplayHelpText)>0,rst_DisplayHelpText,dty_HelpText) as rst_DisplayHelpText", "if(rst_DisplayExtendedDescription is not null and CHAR_LENGTH(rst_DisplayExtendedDescription)>0,rst_DisplayExtendedDescription,dty_ExtendedDescription) as rst_DisplayExtendedDescription", "rst_DisplayOrder", "rst_DisplayWidth", "rst_DefaultValue", "rst_RecordMatchOrder", "rst_CalcFunctionID", "rst_RequirementType", "rst_NonOwnerVisibility", "rst_Status", "rst_OriginatingDBID", "rst_MaxValues", "rst_MinValues", "if(rst_DisplayDetailTypeGroupID is not null,rst_DisplayDetailTypeGroupID,dty_DetailTypeGroupID) as rst_DisplayDetailTypeGroupID", "if(rst_FilteredJsonTermIDTree is not null and CHAR_LENGTH(rst_FilteredJsonTermIDTree)>0,rst_FilteredJsonTermIDTree,dty_JsonTermIDTree) as rst_FilteredJsonTermIDTree", "if(rst_PtrFilteredIDs is not null and CHAR_LENGTH(rst_PtrFilteredIDs)>0,rst_PtrFilteredIDs,dty_PtrTargetRectypeIDs) as rst_PtrFilteredIDs", "rst_OrderForThumbnailGeneration", "rst_TermIDTreeNonSelectableIDs", "rst_Modified", "rst_LocallyModified", "dty_TermIDTreeNonSelectableIDs", "dty_FieldSetRectypeID");
    $query = "select " . join(",", $colNames) . " from defRecStructure" . " left join defDetailTypes on rst_DetailTypeID = dty_ID" . " left join defDetailTypeGroups on dtg_ID = if(rst_DisplayDetailTypeGroupID is not null,rst_DisplayDetailTypeGroupID,dty_DetailTypeGroupID)" . " order by rst_RecTypeID, rst_DisplayOrder, rst_ID";
    $res = mysql_query($query);
    $rtStructs = array('groups' => getRectypeGroups(), 'names' => array(), 'pluralNames' => array(), 'usageCount' => getRecTypeUsageCount(), 'dtDisplayOrder' => array());
    $rtStructs['typedefs'] = array('commonFieldNames' => getRectypeColNames(), 'commonNamesToIndex' => getColumnNameToIndex(getRectypeColNames()), 'dtFieldNamesToIndex' => getColumnNameToIndex(getRectypeStructureFieldColNames()), 'dtFieldNames' => getRectypeStructureFieldColNames());
    while ($row = mysql_fetch_row($res)) {
        if (!array_key_exists($row[0], $rtStructs['typedefs'])) {
            $rtStructs['typedefs'][$row[0]] = array('dtFields' => array($row[1] => array_slice($row, 2)));
            $rtStructs['dtDisplayOrder'][$row[0]] = array();
        } else {
            $rtStructs['typedefs'][$row[0]]['dtFields'][$row[1]] = array_slice($row, 2);
        }
        array_push($rtStructs['dtDisplayOrder'][$row[0]], $row[1]);
    }
    // get rectypes ordered by the RecType Group order, then by Group Name, then by rectype order in group and then by rectype name
    $query = "select rty_ID, rtg_ID, rtg_Name, " . join(",", getRectypeColNames());
    $query = preg_replace("/rty_ConceptID/", "", $query);
    if ($dbID) {
        //if(trm_OriginatingDBID,concat(cast(trm_OriginatingDBID as char(5)),'-',cast(trm_IDInOriginatingDB as char(5))),'null') as trm_ConceptID
        $query .= " if(rty_OriginatingDBID, concat(cast(rty_OriginatingDBID as char(5)),'-',cast(rty_IDInOriginatingDB as char(5))), concat('{$dbID}-',cast(rty_ID as char(5)))) as rty_ConceptID";
    } else {
        $query .= " if(rty_OriginatingDBID, concat(cast(rty_OriginatingDBID as char(5)),'-',cast(rty_IDInOriginatingDB as char(5))), '') as rty_ConceptID";
    }
    $query .= " from defRecTypes left join defRecTypeGroups  on rtg_ID = rty_RecTypeGroupID" . " order by rtg_Order, rtg_Name, rty_OrderInGroup, rty_Name";
    $res = mysql_query($query);
    while ($row = mysql_fetch_row($res)) {
        array_push($rtStructs['groups'][$rtStructs['groups']['groupIDToIndex'][$row[1]]]['allTypes'], $row[0]);
        if ($row[14]) {
            //rty_ShowInList
            array_push($rtStructs['groups'][$rtStructs['groups']['groupIDToIndex'][$row[1]]]['showTypes'], $row[0]);
        }
        $commonFields = array_slice($row, 3);
        $rtStructs['typedefs'][$row[0]]['commonFields'] = $commonFields;
        $rtStructs['names'][$row[0]] = $row[3];
        $rtStructs['pluralNames'][$row[0]] = $row[8];
    }
    $rtStructs['constraints'] = getAllRectypeConstraint();
    setCachedData($cacheKey, $rtStructs);
    return $rtStructs;
}
function makeTitleMaskHumanReadable($fields, $rtID)
{
    $cols = getRectypeColNames();
    $ind1 = array_search('rty_TitleMask', $cols);
    $ind2 = array_search('rty_CanonicalTitleMask', $cols);
    //$ind2 = array_search('rty_Type', $cols);
    if ($ind2) {
        $fields[$ind2] = $fields[$ind1];
        //keep canonical
    }
    $fields[$ind1] = titlemask_make($fields[$ind1], $rtID, 2, null, _ERR_REP_SILENT);
    return $fields;
}