// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateIdListL( const TInt aIdEntryCount,
        RBuf& aEntryIdList, const TDesC& aColName )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateIdListL"));
    //    Create an list of ids seperated by commas
    if( aIdEntryCount > 0 )
        {
        aEntryIdList.CreateL( aIdEntryCount * ( aColName.Length()
                + KMaxIntNumLength ) - 1 );
        for( TInt i = 0; i < aIdEntryCount; i++ )
            {
            aEntryIdList.Append( aColName );
            aEntryIdList.AppendNum( i );
            if( i != aIdEntryCount - 1 )
                {
                aEntryIdList.Append( KComma );
                }
            }
        }
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateGetEntriesQueryByQueryL(
        const CCaInnerQuery* aQuery, CCaSqlQuery* aSqlQuery )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateGetEntriesQueryByQueryL"));
    RBuf whereStatement;
    whereStatement.CleanupClosePushL();

    TUint flagsOn = aQuery->GetFlagsOn();
    if( flagsOn != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryFlagsOn().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryFlagsOn );
        }

    TUint flagsOff = aQuery->GetFlagsOff();
    if( flagsOff != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryFlagsOff().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryFlagsOff );
        }

    TInt role = aQuery->GetRole();
    if( role != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryRole().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryRole );
        }

    TUint uid = aQuery->GetUid();
    if( uid != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryUid().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryUid );
        }

    const CDesC16ArrayFlat* typeNames = aQuery->GetEntryTypeNames();

    if( typeNames && typeNames->MdcaCount() > 0 )
        {
        RBuf typeNameWhereStatement;
        typeNameWhereStatement.CleanupClosePushL();
        for( TInt i = 0; i < typeNames->MdcaCount(); i++ )
            {
            typeNameWhereStatement.ReAllocL(
                    typeNameWhereStatement.Length()
                    + typeNames->MdcaPoint( i ).Length()
                    + KSingleQuotes().Length() * 2 + KComma().Length() );
            typeNameWhereStatement.Append( KSingleQuotes );
            typeNameWhereStatement.Append( typeNames->MdcaPoint( i ) );
            typeNameWhereStatement.Append( KSingleQuotes );
            if( i != typeNames->MdcaCount() - 1 )
                {
                typeNameWhereStatement.Append( KComma );
                }
            }
        whereStatement.ReAllocL( KAnd().Length()
                + KSQLGetEntryTypeNames().Length()
                + typeNameWhereStatement.Length()
                + whereStatement.Length() );
        whereStatement.Append( KAnd );
        whereStatement.AppendFormat( KSQLGetEntryTypeNames,
                &typeNameWhereStatement );
        CleanupStack::PopAndDestroy( &typeNameWhereStatement );
        }
    
    if( aQuery->GetAttributes().Count() )
        {
        RBuf whereAttributes;
        whereAttributes.CleanupClosePushL();
        whereAttributes.CreateL( KEmpty );
        
        for( TInt j=1; j <= aQuery->GetAttributes().Count(); j++ )
            {
            // at1.AT_NAME = 'Attribute_Name_1' AND at1.AT_VALUE = 'Attribute_VALUE_1'
            TPtrC atrName( aQuery->GetAttributes().operator [](j-1)->Name() );
            TPtrC atrValue( aQuery->GetAttributes().operator [](j-1)->Value() );

            whereAttributes.ReAllocL( whereAttributes.Length() + 2 * KAnd().Length() + 
                    4 * KSingleQuotes().Length() +
                    2 * KMaxIntNumLength + 
                    2 * KAt().Length() + 2 * KDot().Length() + 2 * KEqual().Length() +
                    KColumnAttrName().Length() + KColumnAttrValue().Length() +
                    atrName.Length() + atrValue.Length() );
            
            whereAttributes.Append( KAnd );
            
            whereAttributes.Append( KAt );
            whereAttributes.AppendNum( j );
            whereAttributes.Append( KDot );
            whereAttributes.Append( KColumnAttrName );
            whereAttributes.Append( KEqual );
            whereAttributes.Append( KSingleQuotes );
            whereAttributes.Append( atrName );
            whereAttributes.Append( KSingleQuotes );
            
            whereAttributes.Append( KAnd );
            
            whereAttributes.Append( KAt );
            whereAttributes.AppendNum( j );
            whereAttributes.Append( KDot );
            whereAttributes.Append( KColumnAttrValue );
            whereAttributes.Append( KEqual );
            whereAttributes.Append( KSingleQuotes );
            whereAttributes.Append( atrValue );
            whereAttributes.Append( KSingleQuotes );
            
            }
        
        whereStatement.ReAllocL( whereStatement.Length() + whereAttributes.Length() );
        whereStatement.Append( whereAttributes );
        
        CleanupStack::PopAndDestroy( &whereAttributes );
        }

    RBuf leftJoins;
    leftJoins.CleanupClosePushL();
    leftJoins.CreateL( KEmpty );
    if( aQuery->GetAttributes().Count() )
        {
        for( TInt j=1; j <= aQuery->GetAttributes().Count(); j++ )
            {
            // LEFT JOIN CA_ATTRIBUTE as at1 ON ENTRY_ID = at1.AT_ENTRY_ID
            leftJoins.ReAllocL( leftJoins.Length() + 
                    KLeftJoinCaAttrubute1().Length() + KMaxIntNumLength +
                    KLeftJoinCaAttrubute2().Length() + KMaxIntNumLength +
                    KLeftJoinCaAttrubute3().Length()
                    );
            
            leftJoins.Append( KLeftJoinCaAttrubute1 );
            leftJoins.AppendNum( j );
            leftJoins.Append( KLeftJoinCaAttrubute2 );
            leftJoins.AppendNum( j );
            leftJoins.Append( KLeftJoinCaAttrubute3 );
            }
        }
    
    
    whereStatement.ReAllocL( whereStatement.Length() + 
            KGroupBy().Length() + KColumnEntryId().Length() );
    whereStatement.Append( KGroupBy );
    whereStatement.Append( KColumnEntryId );

    TInt groupId = aQuery->GetParentId();
    RBuf query;
    query.CleanupClosePushL();
    if( groupId > 0 )
        {
        RBuf getListByParentId2withWhere;
        getListByParentId2withWhere.CleanupClosePushL();
        getListByParentId2withWhere.CreateL( KSQLGetListByParentId2().Length() + whereStatement.Length() );
        getListByParentId2withWhere.AppendFormat( KSQLGetListByParentId2, &whereStatement );
        
        query.ReAllocL( KSQLGetListByParentId1().Length() +  leftJoins.Length() +
                getListByParentId2withWhere.Length() );
        query.Append( KSQLGetListByParentId1 );
        query.Append( leftJoins );
        query.Append( getListByParentId2withWhere );
        CleanupStack::PopAndDestroy( &getListByParentId2withWhere );
        }
    else if ( aQuery->GetChildId() > 0 )
        {
        RBuf getListByCildIdwithWhere;
        getListByCildIdwithWhere.CleanupClosePushL();
        getListByCildIdwithWhere.CreateL( KSQLGetListByChildId().Length() + whereStatement.Length() );
        getListByCildIdwithWhere.AppendFormat( KSQLGetListByChildId, &whereStatement );
        
        query.ReAllocL( KSQLGetListByParentId1().Length() +  leftJoins.Length() +
                getListByCildIdwithWhere.Length() );
        query.Append( KSQLGetListByParentId1 );
        query.Append( leftJoins );
        query.Append( getListByCildIdwithWhere );
        CleanupStack::PopAndDestroy( &getListByCildIdwithWhere );
        }
    else
        {
        query.CreateL( KSQLGetList1().Length() );
        query.Append( KSQLGetList1 );
        query.ReAllocL( query.Length() + leftJoins.Length() + KSQLGetList2().Length() );
        query.Append( leftJoins );
        query.Append( KSQLGetList2 );
        if( whereStatement.Length() >= KAnd().Length() )
            {
            TPtrC ptrWhereStatement( whereStatement.Right(
                    whereStatement.Length() - KAnd().Length() ) );
            query.ReAllocL( query.Length() +  KWhere().Length()
                    + ptrWhereStatement.Length() );

            query.Append( KWhere );
            query.Append( ptrWhereStatement );
            }
        }

    CCaInnerQuery::TSortAttribute sort = aQuery->GetSort();
    ModifyQueryForSortOrderL( sort, query, groupId > 0 );

    if( aQuery->GetCount() > 0 )
        {
        query.ReAllocL( query.Length() + KLimit().Length()
                + KMaxIntNumLength );
        query.Append( KLimit );
        TInt limitCount = aQuery->GetCount();
        query.AppendNum( limitCount );
        }

    aSqlQuery->SetQueryL( query );
    CleanupStack::PopAndDestroy( &query );
    CleanupStack::PopAndDestroy( &leftJoins );
    CleanupStack::PopAndDestroy( &whereStatement );
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateAddQueryL( CCaInnerEntry* aEntry,
        RPointerArray<CCaSqlQuery>& aSqlQuery, RSqlDatabase& aSqlDb )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateAddQueryL"));
    CCaSqlQuery* queryIcon = CCaSqlQuery::NewLC( aSqlDb );
    
    TIconType iconType = CaSqlQueryCreator::CheckIconType( aEntry );
    
    if( iconType == EProperIcon )
        {
        CreateAddIconQueryL( aEntry, queryIcon, aSqlDb );
        //add new icon to DB
        aSqlQuery.AppendL( queryIcon );
        CleanupStack::Pop( queryIcon );
        }
    else
        {
        // icon added to DB by another entry or not added
        CleanupStack::PopAndDestroy( queryIcon );
        queryIcon = NULL;
        }

    if( aEntry->GetId() != -1 )
        {
        // check if entry is new and has to be added to DB or just updated
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        if( aEntry->GetId() > 0 )
            {
            //Update query is faster than replace query
            CreateUpdateQueryEntryL( aEntry, query );
            }
        else
            {
            // check if entry's Uid was set
            if( aEntry->GetUid() == 0 )
                {
                if( ( aEntry->GetIconId() == 0 ) && ( queryIcon == NULL ) )
                    {
                    query->SetQueryL( 
                            KSQLInsertToEntryUniqueUidWithoutIcon );
                    }
                else
                    {
                    query->SetQueryL( KSQLInsertToEntryUniqueUid );
                    }
                }
            else
                {
                if( ( aEntry->GetIconId() == 0 ) && ( queryIcon == NULL ) )
                    {
                    query->SetQueryL( KSQLInsertToEntryWithoutIcon );
                    }
                else
                    {
                    query->SetQueryL( KSQLInsertToEntry );
                    }
                }
            }
        query->SetTableType( CCaSqlQuery::EEntryTable );
        aSqlQuery.AppendL( query );
        CleanupStack::Pop( query );
        }
    // remove all entry's attributs from DB
    CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
    query->SetQueryL( KSQLDeleteAttribute );
    aSqlQuery.Append( query );
    query->SetTableType( CCaSqlQuery::EAttributeTable );
    CleanupStack::Pop( query );

    if( aEntry->GetAttributes().Count() > 0 )
        {
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        query->SetQueryL( KSQLInsertToAttribute );
        aSqlQuery.AppendL( query );
        query->SetTableType( CCaSqlQuery::EAttributeTable );
        CleanupStack::Pop( query );
        }
    
    if( iconType == ENullIconToRemove )
        {
        RBuf queryRemoveIcon;
        queryRemoveIcon.CleanupClosePushL();
        queryRemoveIcon.CreateL( KSQLDeleteIconWhereIconId().Length() );
        queryRemoveIcon.Append( KSQLDeleteIconWhereIconId );
        queryRemoveIcon.ReAllocL( KSQLDeleteIconWhereIconId().Length() + KMaxIntNumLength );
        queryRemoveIcon.AppendNum( aEntry->GetIconId() );
        
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        query->SetQueryL( queryRemoveIcon );
        aSqlQuery.AppendL( query );
        query->SetTableType( CCaSqlQuery::EIconTable );
        
        CleanupStack::Pop( query );
        CleanupStack::PopAndDestroy( &queryRemoveIcon );
        }
    }
TBool CConfigureCDSDialog::OkToExitL(TInt aButtonId)
	{
	LOG_MSG( "-> CConfigureCDSDialog::OkToExitL" );
	TBool ret = ETrue;
	TInt err;

	RPointerArray<CEikEdwin> edwins;
	CEikEdwin *edwin = static_cast<CEikEdwin*>(Control(EEdwin1));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin2));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin3));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin4));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin5));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin6));
	edwins.Append(edwin);
	edwin = static_cast<CEikEdwin*>(Control(EEdwin7));
	edwins.Append(edwin);

	switch (aButtonId)
		{
		case EEikBidCancel:
			{
			//RDebug::Print(_L("CConfigureCDSDialog::OkToExitL: Cancel pressed"));
			}
			break;
		case EBidCDSConfigure:
			{
			//RDebug::Print(_L("CConfigureCDSDialog::OkToExitL: iConfs.Count() == %d"), iConfs.Count());
			for (TInt i = 0; ( i < iConfs.Count() ) && ret; i++)
				{
				err = KErrNone;

				HBufC *input = NULL;
				if (edwins[i]->TextLength() > 0)
					{
					input = edwins[i]->GetTextInHBufL();
					}
				if ( ! input )
					{
					LOG_MSG2( "  NULL input for param %d" , i );
					continue;
					}

				//RDebug::Print(_L("CConfigureCDSDialog::OkToExitL: iConfs[i]->Type() == %d"), iConfs[i]->Type());

				switch (iConfs[i]->Type())
					{
					case COptionConfig::ETInt:
					case COptionConfig::ETUInt:
						{
						TLex opts(*input);
						TInt32 conf;
						err = opts.Val(conf);
						if ( err )
							{
							LOG_MSG("  error from opts.Val(conf) -> CConfigureCDSDialog::CEikonEnv::Static()->InfoMsg;" );
							CEikonEnv::Static()->InfoMsg(_L("Value must be an integer"));
							break;
							}

						//RDebug::Print(_L("CConfigureCDSDialog::OkToExitL: conf == %d"), conf);
						iConfs[i]->Value(conf);
						TRAP( err, iCoreDumpSession.SetConfigParameterL( *iConfs[i]) );
						}
						break;

					case COptionConfig::ETFileName:
					case COptionConfig::ETString:
					case COptionConfig::ETSingleEntryEnum:
					case COptionConfig::ETMultiEntryEnum:
						{						
						TRAP( err, iConfs[i]->ValueL(*input) );
						if ( KErrNone == err )
							{
							TRAP( err, iCoreDumpSession.SetConfigParameterL( *iConfs[i]) );
							}
						}
						break;

					case COptionConfig::ETBool:
						if (input->CompareF(_L("True"))== 0)
							{
							iConfs[i]->Value(ETrue);
							iConfs[i]->ValueL(_L("True"));
							}
						else if (input->CompareF(_L("False"))== 0)
							{
							iConfs[i]->Value(EFalse);
							iConfs[i]->ValueL(_L("False"));
							}
						else
							{
							err = KErrCorrupt;
							}

						if ( KErrNone == err )
							{
							TRAP( err, iCoreDumpSession.SetConfigParameterL( *iConfs[i]) );
							}

						break;

					default:
						CEikonEnv::Static()->InfoMsg(_L("Error with parameter type"));
						LOG_MSG( "CConfigureCDSDialog::OkToExitL: none of the above" );
						err = KErrCorrupt;
						break;

					}//switch

				if ( err )
					{
					RBuf errorString;
					CleanupClosePushL( errorString );
					errorString.CreateL( 128 );
					errorString.Append( _L("CDS Error ") ); 
					errorString.AppendNum( err );
					errorString.Append( _L(" setting parameter number ") );
					errorString.AppendNum( i );
					CEikonEnv::InfoWinL( errorString, KNullDesC );
					CleanupStack::PopAndDestroy( &errorString );
					ret = EFalse;
					}
                if(input)
                    {
                    delete input;
                    input = NULL;
                    }
				}
			}
			break;
		default:
			break;
		}

    edwins.Close();
	return ret;
	}