<?php

function create_table( $table, $table_Conf )
{
  global $modo_RAD;

  $path  = ( $modo_RAD )? _CFG_ : _CFG_;
  $nFile = $path . $table . ".config.data.ini";

  $flagINI = false;    // indica se config.data.ini foi lido com sucesso
  $flagConect = false; // indica se conexão com a tabela foi feita com sucesso

  /**
   *  Verifica a existencia do arquivo config.data.ini
   *  ----------------------------------------------------------------------- //
   */
  if( file_exists( $nFile ) )
  {
    $arrINI = readINIfile( $nFile );
    $flagINI = true;
  }else
  {
    /** 
     *  inicializa o .config.data.ini vazio
     */
    $arrINI = reset_arrINI_table( $table );
    /**
     *  grava o arquivo .config.data.ini
     */
    writeINIfile( $nFile, $arrINI, ";", "");

  }// End if( file_exists( $nFile ) )
  //echo"\n<pre>";
  //print_r($arrINI);
  //exit;


  /**
   *  Verifica se esta conectado ao dataSource
   *  ----------------------------------------------------------------------- //
   */
  if( empty( $table_Conf['datasource'] ) )
  {
    //echo('dtsource ['.(($flagINI)?'true':'false') .']'."\n<pre>");
    //print_r($arrINI);
    //exit;
    $arrINI = reset_arrINI_table( $table );
    if( file_exists( $nFile ) )
    {
      /**
       *  reseta o arquivo .config.data.ini
       */
      writeINIfile( $nFile, $arrINI, ";", "" );
    }// End
  }else
  {
    if( $arrINI[ $table ."_data" ][ 'datasource' ] != $table_Conf['datasource'] )
    {
      $arrINI[ $table ."_data" ][ 'datasource' ] = $table_Conf['datasource'];
      writeINIfile( $nFile, $arrINI, ";", "" );
      //echo"dif";//exit;
    }// End
    /**
     *  lê arquivo .config.data.ini do dataSource
     */
    $dts = $path . $table_Conf['datasource'] . '.config.data.ini';
    //echo $table_Conf['data_source'];
    if( file_exists( $dts ) )
    {
      $arrDTS = readINIfile( $dts );
      $host  = $arrDTS['db_conect']['host'];
      $user  = $arrDTS['db_conect']['user'];
      $pass  = $arrDTS['db_conect']['pass'];
      $dbase = $arrDTS['db_conect']['dbase'];

      /**
       *  Conecta com o SGDB
       */
      $con = mysql_connect( $host, $user )
        or die('Erro mysql_connect.');
      $db = mysql_select_db( $dbase, $con)
        or die('Erro select DB.');

      if( $flagINI )
      {
        /**
         *  verifica se existe uma Tabela definida
         */
        if( empty($table_Conf['tabela']) )
        {
          if( isset( $arrINI[ $table . "_field" ] ) )
          {
            $dts = $arrINI[ $table . "_data" ][ 'datasource' ];
            $arrINI = reset_arrINI_table( $table );
            $arrINI[ $table . "_data" ][ 'datasource' ] = $dts;
            writeINIfile($nFile, $arrINI, ";", "");
          }else
          {
            $arrINI[ $table . "_data" ][ 'tabela' ] = "";
            writeINIfile($nFile, $arrINI, ";", "");
          }// End if( isset( $arrINI[ $table . "_data" ][ 'field' ] ) )
        }else
        {
          /**
           *  cria o Arquivo .config.data.ini com as configurações default
           *  para a tabela definida
           */
          $dataSet = $table . "_data";
          $nFile_tabela = $path . $table . ".config.data.ini";
          //echo"conf:".$table_Conf['tabela']." :: ".$arrINI[ $dataSet ]['tabela'];exit;
          
          if( ( $arrINI[ $dataSet ]['datasource'] != $table_Conf['datasource'] ) ||
              ( $arrINI[ $dataSet ]['tabela']     != $table_Conf['tabela'] )     ||
              !isset($arrINI[ $dataSet ]['field'] ) )
          {
            createConfigINI_table( $table_Conf['tabela'], $nFile_tabela, $table, $table_Conf );
          }// End if( $table_Conf['tabela'] != $arrINI[ $dataSet ]['tabela'] )
        }// End if( empty($table_Conf['tabela']) )
        
      }else
      {
        if( empty($table_Conf['tabela']) )
        {
          $dts = $arrINI[ $table . "_data" ][ 'datasource' ];
          $arrINI = reset_arrINI_table( $table );
          $arrINI[ $table . "_data" ][ 'datasource' ] = $dts;
          writeINIfile($nFile, $arrINI, ";", "");
        }else
        {
          $nFile = $path . $table . ".config.data.ini";
          createConfigINI_table( $table_Conf['tabela'], $nFile, $table, $table_Conf );
        }// End if( !empty($table_Conf['tabela']) )
      }// End
      
    }else
    {
      //echo('erro: '.$dts);
      $flagConect = false;
    }// End
  }//

//  writeTO( '  <div >' );
//  writeTO( '  ' );
//  writeTO( '  </div>' );

}// End function create_table( $table, $table_Conf )

function create_table_css( $table,
                           $table_Global )
{
  global $projeto,
         $esquema;
  
  $bg_color   = $esquema[$projeto['esquema']]['ThreeDFace'];
  writeTO( '  #' . $table . '{ '                                );
  writeTO( '    position:absolute;'                             );
  writeTO( '    top:' . $table_Global['top'] . 'px'       . ';' );
  writeTO( '    left:' . $table_Global['left'] . 'px'     . ';' );
  writeTO( '    '                                               );
  writeTO( '    z-index:10;'                                    );
  writeTO( '    '                                               );
  writeTO( '    width:' . $table_Global['width'] . 'px'   . ';' );
  writeTO( '    height:' . $table_Global['height'] . 'px' . ';' );
  writeTO( '    '                                               );
  writeTO( '    background-color:' . $bg_color . ';'                  );
  writeTO( '    }'                                               );
}

/**
 *  criar o arquivo .control.js
 *  ------------------------------------------------------------------------  //
 */
function create_table_control( $modo_RAD )
{
  global $componentes_no_Prj,
         $projeto,
         $esquema;

  $path  = ( defined('STUDIO') )? _CFG_ : _CFG_;

  $nDest = $path . "table.control.js.php";
  $comp  = $componentes_no_Prj;

  $fp = @fopen( $nDest, 'wb' );
  foreach( $comp as $comp_ => $obj_ )
  {
    if( $comp_ == 'table' )
    {
      $nrObj    = 0;
      $arrObj   = array();
      $arrConf  = array();
      $arrMaster = array();
      $arrM_Key  = array();
/**
 *  conta o numero de objetos table no projeto
 *  ------------------------------------------------------------------------  //
 *  e armazena os nomes de cada Objeto no
 *  array $arrObj
 */
      foreach( $obj_ as $i_ => $v_ )
      {
        $arrObj[ $nrObj ] = $i_;
        /**
         *  inclui o arquivo .config.def.php de cada Objeto
         */
        include( $path . $i_ . ".config.def.php" );
        $nConf_ = $i_ . "_Conf";
        $arrConf[$i_] = $$nConf_;

        $nFile = $path . $i_ . ".config.data.ini";
        if( file_exists( $nFile ) )
        {
          $arrINI = readINIfile( $nFile );
        }else
        {
          /**
           *  inicializa o arrINI vazio
           */
          $arrINI = reset_arrINI_table( $i_ );
        }// End if( file_exists( $nFile ) )
        $idx = $i_ . '_data';
        $arrMaster[ $nrObj ] = $arrINI[ $idx ][ 'master' ];
        $arrM_Key[ $nrObj ]  = $arrINI[ $idx ][ 'master_key' ];
        
        $nrObj ++;
      }// End

      writeTO( 'table_obj        = '. $nrObj . ';',          $fp );
      writeTO( 'table_master     = new Array();',        $fp );
      writeTO( 'table_master_key = new Array();',        $fp );
      writeTO( 'table_enabled    = new Array();',        $fp );
      writeTO( ' ',                                   $fp );

      /**
       *  propriedade enable
       */
      $idx = 0;
      foreach( $arrConf as $ind => $val)
      {
        writeTO( 'table_enabled[' . $idx . ']    = ' . $val['enable'] .
                 ';',                                                     $fp );
        writeTO( 'table_master[' . $idx . ']     = "' . $arrMaster[ $idx ] .
                 '";',                                                    $fp );
        writeTO( 'table_master_key[' . $idx . '] = "' . $arrM_Key[ $idx ]  .
                 '";',                                                    $fp );
        writeTO( ' ',                                                     $fp );
        $idx ++;
      }// End foreach($arrConf as $ind => $val)
      writeTO( " ", $fp );

    }// End
  }// End
  
  fclose( $fp );

  return( $nDest );
}// End


function createConfigINI_table( $nTabela, $nFile, $table, $table_Conf )
{
  $arrDescTable = getTableInformationOf( $nTabela );
  //echo("\n<pre>".$nFile);print_r($arrDescTable);exit;
  /**
   *  cria o config.data.ini
   *  =============================================================== //
   *  $nFile = $path . $table . ".config.data.ini";
   */
  $_key_ = "";
  foreach( $arrDescTable['primary'] as $_i_ => $_v_ )
  {
    $_key_ .= $_v_;
    if( $_i_ > 0 ) $_key_ .= ":";
  }// End
//  echo("\n<pre>");print_r($_key_);exit;

  $ix_ = $table . '_data';
  $arrINI[ $ix_ ]['datasource'] = $table_Conf['datasource'];
  $arrINI[ $ix_ ]['tabela']     = $table_Conf['tabela'];
  $arrINI[ $ix_ ]['auto']       = $arrDescTable['auto'];
  $arrINI[ $ix_ ]['pk']         = $_key_;
  $arrINI[ $ix_ ]['master']     = $table_Conf['master'];
  $arrINI[ $ix_ ]['master_key'] = $table_Conf['master_key'];

//echo("\n<pre>".$nFile);print_r($arrDescTable['fields']);exit;
  foreach( $arrDescTable['fields'] as $i => $fields )
  {
    //echo("\n$i \n");
    //print_r( $fields );
    $nx_ = "field" . ($i +1);
    $_null_ = ( $fields['Null'] == 'YES' ) ?'true':'false';
    $arrINI[ $table . '_field' ][ $i ] = $nx_;
//    $arrINI[ $table . '_field'][$nx_] = $fields['Field'];

    $arrINI[ $table . '_'.$nx_]['field']   = $fields['Field'];
    $arrINI[ $table . '_'.$nx_]['type']    = $fields['Type'];
    $arrINI[ $table . '_'.$nx_]['null']    = $_null_;
    $arrINI[ $table . '_'.$nx_]['key']     = $fields['Key'];
    $arrINI[ $table . '_'.$nx_]['default'] = $fields['Default'];
    $arrINI[ $table . '_'.$nx_]['extra']   = $fields['Extra'];

    
  }// End foreach( $arrDescTable['fields'] as $i=>$fields )
  writeINIfile($nFile, $arrINI, ";", "");
}// End function createConfigINI_table( $nTabela, $nFile, $table, $table_Conf )




/**
 *  reseta o .config.data.ini
 */
function reset_arrINI_table( $table_ )
{
  $arr_INI = array();
  $ix_ = $table_ . '_data';
  $arr_INI[ $ix_ ][ 'datasource' ] = '';
  $arr_INI[ $ix_ ][ 'tabela' ]     = '';
  $arr_INI[ $ix_ ][ 'auto' ]       = '';
  $arr_INI[ $ix_ ][ 'pk' ]         = '';
  $arr_INI[ $ix_ ][ 'master' ]     = '';
  $arr_INI[ $ix_ ][ 'master_key' ] = '';

//  $arr_INI[ $table_ . '_field']['field1']   = 'field' ;
//  $arr_INI[ $table_ . '_field1']['field']   = ' ';
//  $arr_INI[ $table_ . '_field1']['type']    = 'varchar(10)';
//  $arr_INI[ $table_ . '_field1']['null']    = 'false';
//  $arr_INI[ $table_ . '_field1']['key']     = '';
//  $arr_INI[ $table_ . '_field1']['default'] = '';
//  $arr_INI[ $table_ . '_field1']['extra']   = '';

  return( $arr_INI );
}// End


function conectarTO( $dts, $path )
{
  $ret = true;
  $fileDts = $path . $dts . '.config.data.ini';
  if( file_exists( $fileDts ) )
  {
    $arrDTS = readINIfile( $fileDts );
    $host  = $arrDTS['db_conect']['host'];
    $user  = $arrDTS['db_conect']['user'];
    $pass  = $arrDTS['db_conect']['pass'];
    $dbase = $arrDTS['db_conect']['dbase'];

    /**
     *  Conecta com o SGDB
     */
    $con = mysql_connect( $host, $user )
      or $ret = false;
    $db = mysql_select_db( $dbase, $con)
      or $ret = false;
  }// End
  return( ($ret) ? $db:$ret );
}// End function conectarTO( $dts, $path )




?>
