/**
 * returns an array of detailType structured information for all detailTypes
 *     detailTypes = {"groups" => {"groupIDToIndex":{detailTypeGroupID:index},
 *                                       index:{propName:val,...},...},
 *                    "names":{dtyID:name,...},
 *                    "rectypeUsage" => { dtyID => [rtyID,...], ...},
 *                    'usageCount' => {dtyID:nonzero-count,...},
 *                    "typedefs":{"commonFieldNames":[defDetailTypes Column names],
 *                                "commonNamesToIndex":{"defDetailTypes columnName":index,...},
 *                                dtyID:{"commonFields":[val,....]},
 *                                ...},
 *                    'lookups' => {basetype=>displayName);
 *
 * @global    int $dbID databse ID
 * @param     boolean $useCachedData if true does a lookup for the detailtypes structure in cache
 * @return    object information describing all the detailtypes defined in the database
 * @uses      getDetailTypeColNames()
 * @uses      getColumnNameToIndex()
 * @uses      getRectypeStructureFieldColNames()
 * @uses      getDetailTypeGroups()
 * @uses      getDetailTypeUsageCount()
 * @uses      getDetailTypeDefUsage()
 * @uses      getDtLookups()
 * @uses      getCachedData()
 * @uses      setCachedData()
 */
function getAllDetailTypeStructures($useCachedData = false)
{
    global $dbID;
    $cacheKey = DATABASE . ":AllDetailTypeInfo";
    if ($useCachedData) {
        $dtStructs = getCachedData($cacheKey);
        if ($dtStructs) {
            return $dtStructs;
        }
    }
    $dtG = getDetailTypeGroups();
    /*****DEBUG****/
    //error_log(print_r($dtG,true));
    $dtStructs = array('groups' => $dtG, 'names' => array(), 'rectypeUsage' => getDetailTypeDefUsage(), 'usageCount' => getDetailTypeUsageCount(), 'typedefs' => array('commonFieldNames' => getDetailTypeColNames(), 'fieldNamesToIndex' => getColumnNameToIndex(getDetailTypeColNames())), 'lookups' => getDtLookups());
    $query = "select dtg_ID, dtg_Name, " . join(",", getDetailTypeColNames());
    $query = preg_replace("/dty_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(dty_OriginatingDBID, concat(cast(dty_OriginatingDBID as char(5)),'-',cast(dty_IDInOriginatingDB as char(5))), concat('{$dbID}-',cast(dty_ID as char(5)))) as dty_ConceptID";
    } else {
        $query .= " if(dty_OriginatingDBID, concat(cast(dty_OriginatingDBID as char(5)),'-',cast(dty_IDInOriginatingDB as char(5))), '') as dty_ConceptID";
    }
    $query .= " from defDetailTypes left join defDetailTypeGroups  on dtg_ID = dty_DetailTypeGroupID" . " order by dtg_Order, dtg_Name, dty_OrderInGroup, dty_Name";
    $res = mysql_query($query);
    $dtStructs['sortedNames'] = mysql__select_assoc('defDetailTypes', 'dty_Name', 'dty_ID', '1 order by dty_Name');
    while ($row = mysql_fetch_row($res)) {
        array_push($dtStructs['groups'][$dtG['groupIDToIndex'][$row[0]]]['allTypes'], $row[2]);
        if ($row[17]) {
            // dty_ShowInLists
            array_push($dtStructs['groups'][$dtG['groupIDToIndex'][$row[0]]]['showTypes'], $row[2]);
        }
        $dtStructs['typedefs'][$row[2]]['commonFields'] = array_slice($row, 2);
        $dtStructs['names'][$row[2]] = $row[3];
    }
    setCachedData($cacheKey, $dtStructs);
    /*****DEBUG****/
    //error_log(print_r($dtStructs['typedefs'],true));
    return $dtStructs;
}
/**
 * returns an array of detailType structured information for all detailTypes
 *     detailTypes = {"groups" => {"groupIDToIndex":{detailTypeGroupID:index},
 *                                       index:{propName:val,...},...},
 *                    "names":{dtyID:name,...},
 *                    "rectypeUsage" => { dtyID => [rtyID,...], ...},
 *                    'usageCount' => {dtyID:nonzero-count,...},
 *                    "typedefs":{"commonFieldNames":[defDetailTypes Column names],
 *                                "commonNamesToIndex":{"defDetailTypes columnName":index,...},
 *                                dtyID:{"commonFields":[val,....]},
 *                                ...},
 *                    'lookups' => {basetype=>displayName);
 *
 * @global    int $dbID databse ID
 * @param     boolean $useCachedData if true does a lookup for the detailtypes structure in cache
 * @return    object information describing all the detailtypes defined in the database
 * @uses      getDetailTypeColNames()
 * @uses      __getColumnNameToIndex()
 * @uses      __getRectypeStructureFieldColNames()
 * @uses      getDetailTypeGroups()
 * @uses      getDetailTypeUsageCount()
 * @uses      getDetailTypeDefUsage()
 * @uses      dbs_GetDtLookups()
 * @uses      getCachedData()
 * @uses      setCachedData()
 *
 * $dettypeids null means all, otherwise comma separated list of ids  or list of field types (numeric,blocktext etc)
 * $imode  0 - only names and groupnames
 *         1 - only structure
 *         2 - full, both headers and structures
 *         3 - ids only
 */
function dbs_GetDetailTypes($system, $dettypeids = null, $imode)
{
    $mysqli = $system->get_mysqli();
    $dbID = $system->get_system('sys_dbRegisteredID');
    /*  ARTEM
        global $mysqli, $dbID;
        $cacheKey = DATABASE . ":AllDetailTypeInfo";
        if ($useCachedData) {
        $dtStructs = getCachedData($cacheKey);
        if ($dtStructs) {
        return $dtStructs;
        }
        }
        */
    $dtStructs = array();
    if ($imode != 1) {
        $dtG = getDetailTypeGroups($mysqli);
        $dtStructs['groups'] = $dtG;
        $dtStructs['names'] = array();
    }
    if ($imode > 0) {
        $dtStructs['typedefs'] = array('commonFieldNames' => getDetailTypeColNames(), 'fieldNamesToIndex' => __getColumnNameToIndex(getDetailTypeColNames()));
        $dtStructs['lookups'] = dbs_GetDtLookups();
    }
    if (false && $imode == 2) {
        $dtStructs['rectypeUsage'] = getDetailTypeDefUsage($mysqli);
        $dtStructs['usageCount'] = getDetailTypeUsageCount($mysqli);
    }
    $where_exp = null;
    if ($dettypeids != null || $dettypeids != '' && $dettypeids != 'all') {
        if (!is_array($dettypeids)) {
            $dettypeids = array($dettypeids);
        }
        if ($dettypeids[0] != 'all') {
            //detect ID or TYPE
            if (is_int($dettypeids[0])) {
                $where_exp = ' dty_ID in (' . implode(',', $dettypeids) . ')';
            } else {
                $where_exp = ' dty_Type in (\'' . implode("','", $dettypeids) . '\')';
            }
        }
    }
    if ($imode == 3) {
        //ids only
        //$query = "select dty_ID from defDetailTypes";
        if ($where_exp == null) {
            $where_exp = '';
        }
        $res = mysql__select_list($mysqli, 'defDetailTypes', 'dty_ID', $where_exp);
        return $res;
    } else {
        $query = "select dtg_ID, dtg_Name, " . join(",", getDetailTypeColNames());
        $query = preg_replace("/dty_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(dty_OriginatingDBID, concat(cast(dty_OriginatingDBID as char(5)),'-',cast(dty_IDInOriginatingDB as char(5))), concat('{$dbID}-',cast(dty_ID as char(5)))) as dty_ConceptID";
        } else {
            $query .= " if(dty_OriginatingDBID, concat(cast(dty_OriginatingDBID as char(5)),'-',cast(dty_IDInOriginatingDB as char(5))), '') as dty_ConceptID";
        }
        $query .= " from defDetailTypes left join defDetailTypeGroups  on dtg_ID = dty_DetailTypeGroupID";
        if ($where_exp != null) {
            $query = $query . ' where ' . $where_exp;
        }
        $query = $query . " order by dtg_Order, dtg_Name, dty_OrderInGroup, dty_Name";
    }
    $res = $mysqli->query($query);
    //ARTEM    $dtStructs['sortedNames'] = mysql__select_assoc('defDetailTypes', 'dty_Name', 'dty_ID', '1 order by dty_Name');
    try {
        if (!$res) {
            error_log('FAILED QUERY: ' . $mysqli->error);
            //$query);
            error_log('Database: ' . HEURIST_DBNAME);
        } else {
            while ($row = $res->fetch_row()) {
                if ($imode != 1) {
                    array_push($dtStructs['groups'][$dtG['groupIDToIndex'][$row[0]]]['allTypes'], $row[2]);
                    if ($row[17]) {
                        // dty_ShowInLists
                        array_push($dtStructs['groups'][$dtG['groupIDToIndex'][$row[0]]]['showTypes'], $row[2]);
                    }
                    $dtStructs['names'][$row[2]] = $row[3];
                }
                $dtStructs['typedefs'][$row[2]]['commonFields'] = array_slice($row, 2);
            }
        }
    } catch (Exception $e) {
        //trying to find veird error - missed trm_Modified column
        error_log('Message: ' . $e->getMessage());
        error_log('QUERY: ' . $query);
        error_log('Database: ' . HEURIST_DBNAME);
    }
    //SPECIAL CASE for relation type #6
    if ($imode > 0 && @$dtStructs['typedefs'][DT_RELATION_TYPE]) {
        $idx = $dtStructs['typedefs']['fieldNamesToIndex']['dty_JsonTermIDTree'];
        $dtStructs['typedefs'][DT_RELATION_TYPE]['commonFields'][$idx] = 0;
        $idx = $dtStructs['typedefs']['fieldNamesToIndex']['dty_TermIDTreeNonSelectableIDs'];
        $dtStructs['typedefs'][DT_RELATION_TYPE]['commonFields'][$idx] = '';
    }
    //ARTEM setCachedData($cacheKey, $dtStructs);
    return $dtStructs;
}