text:
#include "ogr_cartodb.h"

CPL_CVSID("$Id: ogrcartodbdatasource.cpp 27268 2014-05-01 10:46:20Z rouault $");

/************************************************************************/
/*                        OGRCARTODBDataSource()                        */
/************************************************************************/

OGRCARTODBDataSource::OGRCARTODBDataSource()

{
    papoLayers = NULL;
    nLayers = 0;

    pszName = NULL;
    pszAccount = NULL;

    bReadWrite = FALSE;
    bUseHTTPS = FALSE;

    bMustCleanPersistant = FALSE;
}

/************************************************************************/
/*                       ~OGRCARTODBDataSource()                        */
/************************************************************************/

OGRCARTODBDataSource::~OGRCARTODBDataSource()

{
    for( int i = 0; i < nLayers; i++ )
        delete papoLayers[i];
    CPLFree( papoLayers );

    if (bMustCleanPersistant)
    {
        char** papszOptions = CSLAddString(NULL, CPLSPrintf("CLOSE_PERSISTENT=CARTODB:%p", this));
        CPLHTTPFetch( GetAPIURL(), papszOptions);
        CSLDestroy(papszOptions);
    }

    CPLFree( pszName );
    CPLFree( pszAccount );
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int OGRCARTODBDataSource::TestCapability( const char * pszCap )

{
    if( bReadWrite && EQUAL(pszCap,ODsCCreateLayer) )
        return TRUE;
    else if( bReadWrite && EQUAL(pszCap,ODsCDeleteLayer) )
        return TRUE;
    else
        return FALSE;
}

/************************************************************************/
/*                              GetLayer()                              */
/************************************************************************/

OGRLayer *OGRCARTODBDataSource::GetLayer( int iLayer )

{
    if( iLayer < 0 || iLayer >= nLayers )
        return NULL;
    else
        return papoLayers[iLayer];
}

/************************************************************************/
/*                          GetLayerByName()                            */
/************************************************************************/

OGRLayer *OGRCARTODBDataSource::GetLayerByName(const char * pszLayerName)
{
    OGRLayer* poLayer = OGRDataSource::GetLayerByName(pszLayerName);
    return poLayer;
}

/************************************************************************/
/*                     OGRCARTODBGetOptionValue()                       */
/************************************************************************/

CPLString OGRCARTODBGetOptionValue(const char* pszFilename,
                               const char* pszOptionName)
{
    CPLString osOptionName(pszOptionName);
    osOptionName += "=";
    const char* pszOptionValue = strstr(pszFilename, osOptionName);
    if (!pszOptionValue)
        return "";

    CPLString osOptionValue(pszOptionValue + strlen(osOptionName));
    const char* pszSpace = strchr(osOptionValue.c_str(), ' ');
    if (pszSpace)
        osOptionValue.resize(pszSpace - osOptionValue.c_str());
    return osOptionValue;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

int OGRCARTODBDataSource::Open( const char * pszFilename, int bUpdateIn)

{
    if (!EQUALN(pszFilename, "CARTODB:", strlen("CARTODB:")))
        return FALSE;

    bReadWrite = bUpdateIn;

    pszName = CPLStrdup( pszFilename );
    pszAccount = CPLStrdup(pszFilename + strlen("CARTODB:"));
    char* pchSpace = strchr(pszAccount, ' ');
    if( pchSpace )
        *pchSpace = '\0';

    osAPIKey = CPLGetConfigOption("CARTODB_API_KEY", "");

    CPLString osTables = OGRCARTODBGetOptionValue(pszFilename, "tables");

    bUseHTTPS = CSLTestBoolean(CPLGetConfigOption("CARTODB_HTTPS", "YES"));

    if (osTables.size() != 0)
    {
        char** papszTables = CSLTokenizeString2(osTables, ",", 0);
        for(int i=0;papszTables && papszTables[i];i++)
        {
            papoLayers = (OGRLayer**) CPLRealloc(
                papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
            papoLayers[nLayers ++] = new OGRCARTODBTableLayer(this, papszTables[i]);
        }
        CSLDestroy(papszTables);
        return TRUE;
    }

    if( osAPIKey.size() == 0 )
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "When not specifying tables option, CARTODB_API_KEY must be defined");
        return FALSE;
    }

    json_object* poObj = RunSQL("SELECT CDB_UserTables()");
    if( poObj == NULL )
        return FALSE;
    json_object* poRows = json_object_object_get(poObj, "rows");
    if( poRows == NULL || json_object_get_type(poRows) != json_type_array)
    {
        json_object_put(poObj);
        return FALSE;
    }
    for(int i=0; i < json_object_array_length(poRows); i++)
    {
        json_object* poTableNameObj = json_object_array_get_idx(poRows, i);
        if( poTableNameObj != NULL &&
            json_object_get_type(poTableNameObj) == json_type_object )
        {
            json_object* poVal = json_object_object_get(poTableNameObj, "cdb_usertables");
            if( poVal != NULL &&
                json_object_get_type(poVal) == json_type_string )
            {
                papoLayers = (OGRLayer**) CPLRealloc(
                    papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
                papoLayers[nLayers ++] = new OGRCARTODBTableLayer(
                            this, json_object_get_string(poVal));
            }
        }
    }
    json_object_put(poObj);

    return TRUE;
}

/************************************************************************/
/*                            GetAPIURL()                               */
/************************************************************************/

const char* OGRCARTODBDataSource::GetAPIURL() const
{
    const char* pszAPIURL = CPLGetConfigOption("CARTODB_API_URL", NULL);
    if (pszAPIURL)
        return pszAPIURL;
    else if (bUseHTTPS)
        return CPLSPrintf("https://%s.cartodb.com/api/v2/sql", pszAccount);
    else
        return CPLSPrintf("http://%s.cartodb.com/api/v2/sql", pszAccount);
}

/************************************************************************/
/*                             FetchSRSId()                             */
/************************************************************************/

int OGRCARTODBDataSource::FetchSRSId( OGRSpatialReference * poSRS )

{
    const char*         pszAuthorityName;

    if( poSRS == NULL )
        return 0;

    OGRSpatialReference oSRS(*poSRS);
    poSRS = NULL;

    pszAuthorityName = oSRS.GetAuthorityName(NULL);

    if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 )
    {
/* -------------------------------------------------------------------- */
/*      Try to identify an EPSG code                                    */
/* -------------------------------------------------------------------- */
        oSRS.AutoIdentifyEPSG();

        pszAuthorityName = oSRS.GetAuthorityName(NULL);
        if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG"))
        {
            const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL);
            if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 )
            {
                /* Import 'clean' SRS */
                oSRS.importFromEPSG( atoi(pszAuthorityCode) );

                pszAuthorityName = oSRS.GetAuthorityName(NULL);
            }
        }
    }
/* -------------------------------------------------------------------- */
/*      Check whether the EPSG authority code is already mapped to a    */
/*      SRS ID.                                                         */
/* -------------------------------------------------------------------- */
    if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) )
    {
        int             nAuthorityCode;

        /* For the root authority name 'EPSG', the authority code
         * should always be integral
         */
        nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) );

        return nAuthorityCode;
    }

    return 0;
}

/************************************************************************/
/*                           CreateLayer()                              */
/************************************************************************/

OGRLayer   *OGRCARTODBDataSource::CreateLayer( const char *pszName,
                                           OGRSpatialReference *poSpatialRef,
                                           OGRwkbGeometryType eGType,
                                           char ** papszOptions )
{
    if (!bReadWrite)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode");
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Do we already have this layer?  If so, should we blow it        */
/*      away?                                                           */
/* -------------------------------------------------------------------- */
    int iLayer;

    for( iLayer = 0; iLayer < nLayers; iLayer++ )
    {
        if( EQUAL(pszName,papoLayers[iLayer]->GetName()) )
        {
            if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
                && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
            {
                DeleteLayer( iLayer );
            }
            else
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                          "Layer %s already exists, CreateLayer failed.\n"
                          "Use the layer creation option OVERWRITE=YES to "
                          "replace it.",
                          pszName );
                return NULL;
            }
        }
    }

    int nSRID = 0;
    if( poSpatialRef != NULL )
        nSRID = FetchSRSId( poSpatialRef );

    CPLString osGeomType;
    if( eGType != wkbNone )
    {
        osGeomType = OGRToOGCGeomType(eGType);
        if( eGType & wkb25DBit )
            osGeomType += "Z";
    }

    CPLString osSQL;
    osSQL.Printf("CREATE TABLE %s ( %s SERIAL, ",
                 OGRCARTODBEscapeIdentifier(pszName).c_str(),
                 "cartodb_id");
    if( osGeomType.size() > 0 )
    {
        osSQL += CPLSPrintf("%s GEOMETRY(%s, %d), %s GEOMETRY(%s, %d),",
                 "the_geom",
                 osGeomType.c_str(),
                 nSRID,
                 "the_geom_webmercator",
                 osGeomType.c_str(),
                 3857);
    }
    osSQL += CPLSPrintf("PRIMARY KEY (%s) )", "cartodb_id");

    osSQL += ";";
    osSQL += CPLSPrintf("DROP SEQUENCE IF EXISTS %s",
                        OGRCARTODBEscapeIdentifier(CPLSPrintf("%s_%s_seq", pszName, "cartodb_id")).c_str());
    osSQL += ";";
    osSQL += CPLSPrintf("CREATE SEQUENCE %s START 1",
                        OGRCARTODBEscapeIdentifier(CPLSPrintf("%s_%s_seq", pszName, "cartodb_id")).c_str());
    osSQL += ";";
    osSQL += CPLSPrintf("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT nextval('%s')",
                        pszName,
                        "cartodb_id",
                        OGRCARTODBEscapeLiteral(CPLSPrintf("%s_%s_seq", pszName, "cartodb_id")).c_str());

    json_object* poObj = RunSQL(osSQL);
    if( poObj == NULL )
        return NULL;
    json_object_put(poObj);

    OGRCARTODBTableLayer* poLayer = new OGRCARTODBTableLayer(this, pszName);
    papoLayers = (OGRLayer**) CPLRealloc(
                    papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
    papoLayers[nLayers ++] = poLayer;

    return poLayer;
}

/************************************************************************/
/*                            DeleteLayer()                             */
/************************************************************************/

OGRErr OGRCARTODBDataSource::DeleteLayer(int iLayer)
{
    if (!bReadWrite)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Operation not available in read-only mode");
        return OGRERR_FAILURE;
    }

    if( iLayer < 0 || iLayer >= nLayers )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Layer %d not in legal range of 0 to %d.",
                  iLayer, nLayers-1 );
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Blow away our OGR structures related to the layer.  This is     */
/*      pretty dangerous if anything has a reference to this layer!     */
/* -------------------------------------------------------------------- */
    CPLString osLayerName = papoLayers[iLayer]->GetLayerDefn()->GetName();

    CPLDebug( "CARTODB", "DeleteLayer(%s)", osLayerName.c_str() );

    delete papoLayers[iLayer];
    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
             sizeof(void *) * (nLayers - iLayer - 1) );
    nLayers--;

    if (osLayerName.size() == 0)
        return OGRERR_NONE;

    CPLString osSQL;
    osSQL.Printf("DROP TABLE %s",
                 OGRCARTODBEscapeIdentifier(osLayerName).c_str());

    json_object* poObj = RunSQL(osSQL);
    if( poObj == NULL )
        return OGRERR_FAILURE;
    json_object_put(poObj);

    return OGRERR_NONE;
}

/************************************************************************/
/*                          AddHTTPOptions()                            */
/************************************************************************/

char** OGRCARTODBDataSource::AddHTTPOptions(char** papszOptions)
{
    bMustCleanPersistant = TRUE;

    return CSLAddString(papszOptions, CPLSPrintf("PERSISTENT=CARTODB:%p", this));
}

/************************************************************************/
/*                               RunSQL()                               */
/************************************************************************/

json_object* OGRCARTODBDataSource::RunSQL(const char* pszUnescapedSQL)
{
    CPLString osSQL("POSTFIELDS=q=");
    /* Do post escaping */
    for(int i=0;pszUnescapedSQL[i] != 0;i++)
    {
        const int ch = ((unsigned char*)pszUnescapedSQL)[i];
        if (ch != '&' && ch >= 32 && ch < 128)
            osSQL += (char)ch;
        else
            osSQL += CPLSPrintf("%%%02X", ch);
    }

/* -------------------------------------------------------------------- */
/*      Provide the API Key                                             */
/* -------------------------------------------------------------------- */
    if( osAPIKey.size() )
    {
        osSQL += "&api_key=";
        osSQL += osAPIKey;
    }

/* -------------------------------------------------------------------- */
/*      Collection the header options and execute request.              */
/* -------------------------------------------------------------------- */
    char** papszOptions = CSLAddString(AddHTTPOptions(), osSQL);
    CPLHTTPResult * psResult = CPLHTTPFetch( GetAPIURL(), papszOptions);
    CSLDestroy(papszOptions);

/* -------------------------------------------------------------------- */
/*      Check for some error conditions and report.  HTML Messages      */
/*      are transformed info failure.                                   */
/* -------------------------------------------------------------------- */
    if (psResult && psResult->pszContentType &&
        strncmp(psResult->pszContentType, "text/html", 9) == 0)
    {
        CPLDebug( "CARTODB", "RunSQL HTML Response:%s", psResult->pabyData );
        CPLError(CE_Failure, CPLE_AppDefined,
                 "HTML error page returned by server");
        CPLHTTPDestroyResult(psResult);
        return NULL;
    }
    if (psResult && psResult->pszErrBuf != NULL)
    {
        CPLDebug( "CARTODB", "RunSQL Error Message:%s", psResult->pszErrBuf );
    }
    else if (psResult && psResult->nStatus != 0)
    {
        CPLDebug( "CARTODB", "RunSQL Error Status:%d", psResult->nStatus );
    }

    if( psResult->pabyData == NULL )
    {
        CPLHTTPDestroyResult(psResult);
        return NULL;
    }

    if( strlen((const char*)psResult->pabyData) < 1000 )
        CPLDebug( "CARTODB", "RunSQL Response:%s", psResult->pabyData );

    json_tokener* jstok = NULL;
    json_object* poObj = NULL;

    jstok = json_tokener_new();
    poObj = json_tokener_parse_ex(jstok, (const char*) psResult->pabyData, -1);
    if( jstok->err != json_tokener_success)
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                    "JSON parsing error: %s (at offset %d)",
                    json_tokener_error_desc(jstok->err), jstok->char_offset);
        json_tokener_free(jstok);
        CPLHTTPDestroyResult(psResult);
        return NULL;
    }
    json_tokener_free(jstok);

    CPLHTTPDestroyResult(psResult);

    if( poObj != NULL )
    {
        if( json_object_get_type(poObj) == json_type_object )
        {
            json_object* poError = json_object_object_get(poObj, "error");
            if( poError != NULL && json_object_get_type(poError) == json_type_array &&
                json_object_array_length(poError) > 0 )
            {
                poError = json_object_array_get_idx(poError, 0);
                if( poError != NULL && json_object_get_type(poError) == json_type_string )
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                            "Error returned by server : %s", json_object_get_string(poError));
                    json_object_put(poObj);
                    return NULL;
                }
            }
        }
        else
        {
            json_object_put(poObj);
            return NULL;
        }
    }

    return poObj;
}

/************************************************************************/
/*                        OGRCARTODBGetSingleRow()                      */
/************************************************************************/

json_object* OGRCARTODBGetSingleRow(json_object* poObj)
{
    if( poObj == NULL )
    {
        return NULL;
    }

    json_object* poRows = json_object_object_get(poObj, "rows");
    if( poRows == NULL ||
        json_object_get_type(poRows) != json_type_array ||
        json_object_array_length(poRows) != 1 )
    {
        json_object_put(poObj);
        return NULL;
    }

    json_object* poRowObj = json_object_array_get_idx(poRows, 0);
    if( poRowObj == NULL || json_object_get_type(poRowObj) != json_type_object )
    {
        json_object_put(poObj);
        return NULL;
    }

    return poRowObj;
}

/************************************************************************/
/*                             ExecuteSQL()                             */
/************************************************************************/

OGRLayer * OGRCARTODBDataSource::ExecuteSQL( const char *pszSQLCommand,
                                        OGRGeometry *poSpatialFilter,
                                        const char *pszDialect )

{
    /* Skip leading spaces */
    while(*pszSQLCommand == ' ')
        pszSQLCommand ++;

/* -------------------------------------------------------------------- */
/*      Use generic implementation for recognized dialects              */
/* -------------------------------------------------------------------- */
    if( IsGenericSQLDialect(pszDialect) )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Special case DELLAYER: command.                                 */
/* -------------------------------------------------------------------- */
    if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
    {
        const char *pszLayerName = pszSQLCommand + 9;

        while( *pszLayerName == ' ' )
            pszLayerName++;

        for( int iLayer = 0; iLayer < nLayers; iLayer++ )
        {
            if( EQUAL(papoLayers[iLayer]->GetName(),
                      pszLayerName ))
            {
                DeleteLayer( iLayer );
                break;
            }
        }
        return NULL;
    }

    OGRCARTODBResultLayer* poLayer = new OGRCARTODBResultLayer( this, pszSQLCommand );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

    CPLErrorReset();
    poLayer->GetLayerDefn();
    if( CPLGetLastErrorNo() != 0 )
    {
        delete poLayer;
        return NULL;
    }

    return poLayer;
}

/************************************************************************/
/*                          ReleaseResultSet()                          */
/************************************************************************/

void OGRCARTODBDataSource::ReleaseResultSet( OGRLayer * poLayer )

{
    delete poLayer;
}


text:
@interface ContactViewController (){
    // Dungnm8
    dispatch_queue_t processQueue;
    NSMutableArray *listAllContact;
    ContactDetial * contactDetial;
    NSMutableArray * tmpReengFirst;
    NSMutableArray * listRengContact;
    @private
    NSString * idRosterAll;
    NSString * idRosterOne;

    NSDictionary *plistDic;
    CGRect _detailFrameMenu, _detailFrameAction;
    BOOL isPhoneCountMore;
    ChatViewDetail * chatViewDetail;
    UIActionSheet * alerLongClick;

    //Luc
    NSIndexPath *indexDelete;
    Person* sPerson;
    NSString *strName;
    CGFloat _y;
    CGFloat _x;
    UIActionSheet *aac;
    ABAddressBookRef addressBook;
    ABRecordRef personRef;
    ABPersonViewController *picker;
    UINavigationController *navController;
    // Phan  munti delete
    BOOL checkSelectAll;//0 bo chon ;1 select ;2 select all
    BOOL checkDelete;
    BOOL checkHideMenu;
    NSMutableArray * listSelected;
    UILongPressGestureRecognizer *recognizer;
    // check user search
    BOOL isFinter;
    NSMutableArray * listContactDB;
}

@end

@implementation ContactViewController

@synthesize objAuthen,mainViewController;
@synthesize tableContacts,listContact,filteredTableData,uISearchBar;
@synthesize btnReengContact, btnContact, btnLikeReeng, btnEditContact;
@synthesize frameMenu;

@synthesize indicatoView;

@synthesize btnMenuAdd,btnMenuDelete;
@synthesize btnDeleteContact,btnCheck,btnCancel,detaiMenuAction;

@synthesize segment;

// LucTp
@synthesize defaultRightBarButtonItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        processQueue = dispatch_queue_create("get contact process queue", NULL);

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    objAuthen = [(AppDelegate *)[[UIApplication sharedApplication] delegate] objAuthen];
    [objAuthen.messageParser addDelegate:self];
    [objAuthen.reengData addDelegate:self];

    recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(handleLongPress:)];
    [recognizer setMinimumPressDuration:0.4];
    [tableContacts addGestureRecognizer:recognizer];

    if (self.savedSearchTerm)
	{
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:_savedSearchTerm];
        self.savedSearchTerm = nil;
    }

    // khoi tao duong dan file
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"property" ofType:@"plist"];
    plistDic = [[NSDictionary alloc]initWithContentsOfFile:filePath];
    [self loadDataContact];

}

#pragma mark ham khoi tao du lieu
-(void)initialData{
    // khoi tao cac mang
    [self createAddressBook];

    ABAddressBookRegisterExternalChangeCallback(addressBook, MyAddressBookExternalChangeCallback, (__bridge void *)(self));
    listAllContact = [[NSMutableArray alloc] init];
    listRengContact =[[NSMutableArray alloc] init];
    listContact = [[NSMutableArray alloc] init];
    tmpReengFirst = [[NSMutableArray alloc]init];
    filteredTableData = [[NSMutableArray alloc]init];

    // khoi tao doi tuong addressBook
    checkDelete = NO;
    checkSelectAll = NO;
    isFinter = NO;

}

#pragma mark ham xoa toan bo cache
- (void)flushCache
{
    [SDWebImageManager.sharedManager.imageCache clearMemory];
    [SDWebImageManager.sharedManager.imageCache clearDisk];
}

#pragma mark ham lay du lieu trong db va gui du lieu len server
- (void) loadDataContact{
    [self initialData];
     dispatch_async(processQueue, ^{@autoreleasepool {
         [self getAllContactDb];
         [objAuthen.reengData.listAllContacts removeAllObjects];
         [objAuthen.reengData.listRengContacts removeAllObjects];
         objAuthen.reengData.listAllContacts = listAllContact;

         listRengContact = [self getListReeng];
//         [self getListReeng];
         objAuthen.reengData.listRengContacts = listRengContact;

         idRosterAll = [UtilContactDetail createUUIDSendContact:objAuthen];

         [UtilContactDetail sendAllContact:objAuthen idRosterAll:idRosterAll listPhone:listAllContact];

         [UtilContactDetail getListBlockContact:objAuthen];

         [self getlistAllContact];
         // goi ham cap nhat la du lieu
         [objAuthen.reengData setDidUpdateContact];
     }});
}
#pragma mark ham thong bao du lieu db da thay doi
-(void)onDidUpdateContact{
    [self.tableContacts reloadData];
    [indicatoView stopAnimating];
}

- (void)viewWillAppear:(BOOL)animated {
    // An phan giao dien search

    CGRect newBounds = self.tableContacts.bounds;
    newBounds.origin.y = newBounds.origin.y + self.uISearchBar.bounds.size.height;
    self.tableContacts.bounds = newBounds;
}

- (void)viewWillDisappear:(BOOL)animated
{

    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
    [super viewWillDisappear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    _detailFrameMenu = frameMenu.frame;
    _detailFrameAction = detaiMenuAction.frame;
    listSelected = [[NSMutableArray alloc] init];
}

#pragma mark lay danh sach contact trong db
-(void) getAllContactDb{
    @try {
        if([DatabaseHelper isCheckDbExists]){
            listAllContact = [DatabaseHelper getAllContact];
        }
    }
    @catch (NSException *exception) {
        NSLog(@"khong lay duoc thong tin db %@",exception.name);
    }
}

#pragma mark lay danh sanh like contact
-(NSMutableArray *)getListLike{
    NSMutableArray * listLike = [[NSMutableArray alloc]init];
    @try {
        for (Person * objPerson in listAllContact) {
            if(objPerson.isFavorite == 1){
                [listLike addObject:objPerson];
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"khong lay duoc thong tin db %@",exception.name);
    }
    return listLike;
}

#pragma mark lay danh sanh like contact
-(NSMutableArray *)getListReeng{
    NSMutableArray * listReeng = [[NSMutableArray alloc]init];
    @try {
        for (Person * objPerson in listAllContact) {
            for (PhoneNumber * objPhone in objPerson.listObjectPhone) {
                if(objPhone.phoneIsReeng == 1){
                    objPerson.status = objPhone.phoneStatus;
                    objPerson.state = @"1";
                    [listReeng addObject:objPerson];
                }
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"khong lay duoc thong tin db %@",exception.name);
    }
    return listReeng;
}

#pragma mark UITableView
/////////////////////////////////////////////////////////////////////////
#pragma mark tableView sectionIndexTitlesForTableView
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }else{
        return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:
            [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
    }
}

#pragma mark tableView:sectionForSectionIndexTitle
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 0;
    } else {
        if (title == UITableViewIndexSearch) {
            [tableView scrollRectToVisible:self.searchDisplayController.searchBar.frame animated:NO];
            return -1;
        } else {
            return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index-1];
        }
    }
}

#pragma mark tableView numberOfSectionsInTableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 1;
	}else{
        return [listContact count];
    }
}

#pragma mark tableView:titleForHeaderInSection
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }else{
        return [[listContact objectAtIndex:section] count] ? [[[UILocalizedIndexedCollation
                                                                currentCollation] sectionTitles] objectAtIndex:section] : nil;
    }

}

#pragma mark tableView:numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [filteredTableData count];
    }else{
        return [[listContact objectAtIndex:section] count];
    }
}

#pragma mark tableView:cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	{
        static NSString *CellIdentifier = @"ContactTableCell";

        ContactTableCell *cell = (ContactTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ContactTableCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        Person *per = nil;
        if (tableView == self.searchDisplayController.searchResultsTableView){
            if(indexPath.row < [filteredTableData count]){
                per = [filteredTableData objectAtIndex:indexPath.row];
            }else{
                return cell;
            }
        }
        else{
            if(indexPath.section < [listContact count] && indexPath.row < [[listContact objectAtIndex:indexPath.section] count]){
                per = [[listContact objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
            }else{
                return cell;
            }
        }
        if([per.fullName isEqualToString:@""]){
            cell.name.text = @"Không rõ";
        }else{
            cell.name.text = per.fullName;
        }
        cell.status.text = per.status;

        if(per.usr_photoUri == nil || [per.usr_photoUri isEqualToString:@""]){
            if(per.imageAvatar == nil){
                per.imageAvatar = [UIImage imageNamed:@"ava-56.png"];
            }
            [cell.icon setImage:per.imageAvatar];
        }else{
            [cell.icon setImageWithURL:[NSURL URLWithString:per.usr_photoUri]placeholderImage:[UIImage imageNamed:@"ava-56.png"]];
        }
        if(!checkDelete){
            if(per.state ==nil ||[per.state isEqualToString:@"0"]){
                [cell.on_Off setImage:nil];
            }else{
                if(per.isOnline == 1){
                    [cell.on_Off setImage:[UIImage imageNamed:@"ic_stat_online.png"]];

                }else{
                    [cell.on_Off setImage:[UIImage imageNamed:@"ic_stat_offline.png"]];
                }
            }

        }else{
            NSLog(checkSelectAll ? @"Yes" : @"No");
            if(checkSelectAll)
            {
                [cell.on_Off setImage:[UIImage imageNamed:@"checkbox_3a.png"]];

            }else{
                if ([listSelected containsObject:per]) {
                    [cell.on_Off setImage:[UIImage imageNamed:@"checkbox_3a.png"]];
                }else{
                    [cell.on_Off setImage:[UIImage imageNamed:@"checkbox_3b.png"]];
                }

            }
        }
        return cell;
    }
}

#pragma mark tableView:heightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70; // your dynamic height...
}

#pragma mark tableView:didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    ContactTableCell *cell = (ContactTableCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        sPerson = [filteredTableData objectAtIndex:indexPath.row];
    }else{
        sPerson=[[listContact objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }
    if(!checkDelete)
    {

        contactDetial=[[ContactDetial alloc]initWithNibName:@"ContactDetial" bundle:nil];
        if(sPerson != nil){
            contactDetial.personObject = sPerson;
            contactDetial.isFromContact = YES;
            contactDetial.objAuthen = objAuthen;
            contactDetial.tableContact = tableContacts;
            contactDetial.mainView = mainViewController;
            contactDetial.contactView=self;
        }
        [Util showNextView:mainViewController.view :contactDetial.view];
        [mainViewController setGes:NO];

    }else
    {
        // checkbox_3a.png  ic_icon_sent_ok.png
        // checkbox_3b.png ic_icon_ok_black.png
        if ([listSelected containsObject:sPerson]) {
            [listSelected removeObject:sPerson];
            [cell.on_Off setImage:[UIImage imageNamed:@"checkbox_3b.png"]];
            if([listSelected count]<[listAllContact count])
            {
                [btnCheck setImage:[UIImage imageNamed:@"checkbox_3b.png"] forState:UIControlStateNormal] ;
                checkSelectAll = NO;
            }
        } else{

            [listSelected addObject:sPerson];
            if([listSelected count]==[listAllContact count])
            {
                [btnCheck setImage:[UIImage imageNamed:@"checkbox_3a.png"] forState:UIControlStateNormal] ;
                checkSelectAll = YES;
            }
            [cell.on_Off setImage:[UIImage imageNamed:@"checkbox_3a.png"]];
        }
    }
    if (checkHideMenu) {
        checkHideMenu = NO;
        [self hideShowAddOrDeleteMenu];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)_searchBar
{
    segment.userInteractionEnabled = NO;
	[self.searchDisplayController.searchBar setShowsCancelButton:NO];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)_searchBar
{
	[self.searchDisplayController setActive:NO animated:YES];
    segment.userInteractionEnabled = YES;
	[self.tableContacts reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)_searchBar
{
    segment.userInteractionEnabled = YES;
	[self.searchDisplayController setActive:YES animated:YES];
    [self.view endEditing:YES];
    [self.tableContacts reloadData];
	self.tableContacts.scrollEnabled = YES;
}

#pragma mark ContentFiltering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSMutableArray  * tmpSearch = [[NSMutableArray alloc]init];
    BOOL isCheckSearchPhone;

    if([searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length > 0 ){

        isFinter = YES;
        if (isFinter) {
            recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                       action:@selector(handleLongPress:)];
            [recognizer setMinimumPressDuration:0.4];
            [self.searchDisplayController.searchResultsTableView addGestureRecognizer:recognizer];
        }

        for (NSArray *section in listContact) {
            for (Person * personSearch in section){
                NSRange name = [personSearch.fullName  rangeOfString:[searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] options:NSCaseInsensitiveSearch];
                 isCheckSearchPhone = NO;
                for (PhoneNumber *strphone in personSearch.listObjectPhone) {
                    NSRange phone = [strphone.phoneNumber  rangeOfString:[searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] options:NSCaseInsensitiveSearch];
                    if(phone.location != NSNotFound && phone.length > 0 )
                    {
                        isCheckSearchPhone = YES;
                        break;
                    }
                }
                if((name.location != NSNotFound && name.length > 0)|| isCheckSearchPhone){
                    [tmpSearch addObject:personSearch];
                }
            }
        }
        filteredTableData = tmpSearch;
        tmpReengFirst = nil;
    }

}

#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    segment.userInteractionEnabled = NO;
    [self filterContentForSearchText:searchString scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    segment.userInteractionEnabled = NO;

    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

#pragma mark ham bat su kien on/off hoac thay doi avatar, va status
-(void)updateReceiverActionContactPresence :(BOOL)isAvailable strShow :(NSString*) strShow status:(NSString *)status strAvatar:(NSString *)strAvatar isRemoveAvatar:(BOOL) isRemoveAvatar idContact:(int) idContact phone_number:(NSString *)phone_number{
    if(isAvailable){
        if(strShow != nil){
            for (Person * per in listAllContact) {
                if(per.idUserContact == idContact){
                    per.state = [NSString stringWithFormat:@"3"];
                    per.isOnline = 0;
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:phone_number]){
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneState = per.state;
                        }
                    }
                }
            }
        }
        else if(status != nil){
            for (Person * per in listAllContact) {
                if(per.idUserContact == idContact){
                    per.status = status;
                }
            }
        }
        else if(strAvatar != nil){
            if(!isRemoveAvatar){
                for (Person * per in listAllContact) {
                    if(per.idUserContact == idContact){
                        per.usr_photoUri = @"";
                        @try {
                            [DatabaseHelper updateContactUserLinkPhoto:idContact usr_name:per.usr_photoUri];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"%@",exception.name);
                        }
                    }
                }
            }else{
                for (Person * per in listAllContact) {
                    if(per.idUserContact == idContact){
                        per.usr_photoUri = [UtilContactDetail getLinkAvatarUrl:phone_number vtCode:[plistDic objectForKey:@"vtCodeImage"] linkUrlImage:[plistDic objectForKey:@"urlImage3G"]];
                        @try {
                            [DatabaseHelper updateContactUserLinkPhoto:idContact usr_name:per.usr_photoUri];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"%@",exception.name);
                        }
                    }
                }
            }
        }
        else{
            for (Person * per in listAllContact) {
                if(per.idUserContact == idContact){
                    per.state = [NSString stringWithFormat:@"2"];
                    per.isOnline = 1;
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:phone_number]){
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneState = per.state;
                        }
                    }
                    if(![listRengContact containsObject:per]){
                        [listRengContact addObject:per];
                        break;
                    }
                }
            }
        }
        [objAuthen.reengData setDidUpdateContact];
    }else{
        if(status != nil){
            for (Person * per in listAllContact) {
                if(per.idUserContact == idContact){
                    per.state = [NSString stringWithFormat:@"0"];
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:phone_number]){
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneState = per.state;
                        }
                    }
                    if([listRengContact containsObject:per]){
                        [listRengContact removeObject:per];
                        break;
                    }
                }
            }
        }else{
            for (Person * per in listAllContact) {
                if(per.idUserContact == idContact){
                    per.state = [NSString stringWithFormat:@"1"];
                    per.isOnline = 0;
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:phone_number]){
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneState = per.state;
                        }
                    }
                }
            }
        }
        [objAuthen.reengData setDidUpdateContact];
    }
}

#pragma mark truong hop nhan ban tin bi loi
-(void)notifiErrorSendContact:(NSString *)idRoster{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Mất kết nối" message:@"Mất kết nối đến server. kiểm tra lại trạng thái mạng" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alertView show];
}

#pragma mark ham nhan ban tin IQ cua
-(void)getListContactIQRosterReceive:(NSString *)idRosterReceive listReengTemp:(NSMutableArray *)listReengTemp{
    if([idRosterReceive isEqualToString:idRosterAll]){
        NSLog(@" sao lai o day the nhi");
        [listRengContact removeAllObjects];
        for (Person* per in listAllContact) {
            for (PhoneNumber * listTem in listReengTemp) {
                if(per.idUserContact == listTem.phoneContactId){
                    if ([listTem.phoneState isEqualToString:@"1"]||[listTem.phoneState isEqualToString:@"3"]) {
                        per.isOnline = 0;
                    }else if ([listTem.phoneState isEqualToString:@"2"]){
                        per.isOnline = 1;
                    }
                    per.status = listTem.phoneStatus;
                    per.state = listTem.phoneState;
                    per.usr_photoUri = [UtilContactDetail getLinkAvatarUrl:listTem.phoneNumber vtCode:[plistDic objectForKey:@"vtCodeImage"] linkUrlImage:[plistDic objectForKey:@"urlImage3G"]];
                    [self flushCache];
                    if(listTem.phoneAvatarLastChange != nil && ![listTem.phoneAvatarLastChange isEqualToString:@""] && [per.lastChangeAvatar isEqualToString:listTem.phoneAvatarLastChange]){
                        @try {
                            [DatabaseHelper updateContactUserLinkPhoto:per.idUserContact usr_name:per.usr_photoUri];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"%@",exception.name);
                        }
                    }
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:listTem.phoneNumber]){
                            objectPhone.phoneIsReeng = 1;
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneStatus = listTem.phoneStatus;
                            objectPhone.phoneState = listTem.phoneState;
                        }
                    }
                    if(![listRengContact containsObject:per]){
                        [listRengContact addObject:per];
                    }
                    break;
                }
            }
        }
        objAuthen.reengData.listRengContacts = listRengContact;
    }else if([idRosterReceive isEqualToString:idRosterOne]){
        for (Person * per in listAllContact) {
            for (PhoneNumber * listTem in listReengTemp) {
                if(per.idUserContact == listTem.phoneContactId){
                    if ([listTem.phoneState isEqualToString:@"1"]||[listTem.phoneState isEqualToString:@"3"]) {
                        per.isOnline = 0;
                    }else if ([listTem.phoneState isEqualToString:@"2"]){
                        per.isOnline = 1;
                    }
                    per.status = listTem.phoneStatus;
                    per.state = listTem.phoneState;
                    per.usr_photoUri = [UtilContactDetail getLinkAvatarUrl:listTem.phoneNumber vtCode:[plistDic objectForKey:@"vtCodeImage"] linkUrlImage:[plistDic objectForKey:@"urlImage3G"]];
                    [self flushCache];
                    if(listTem.phoneAvatarLastChange != nil && ![listTem.phoneAvatarLastChange isEqualToString:@""] && [per.lastChangeAvatar isEqualToString:listTem.phoneAvatarLastChange]){
                        @try {
                            [DatabaseHelper updateContactUserLinkPhoto:per.idUserContact usr_name:per.usr_photoUri];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"%@",exception.name);
                        }
                    }
                    for (PhoneNumber * objectPhone in per.listObjectPhone) {
                        if([objectPhone.phoneNumber isEqualToString:listTem.phoneNumber]){
                            objectPhone.phoneIsReeng = 1;
                            objectPhone.phoneContactName = per.fullName;
                            objectPhone.phoneStatus = listTem.phoneStatus;
                            objectPhone.phoneState = listTem.phoneState;
                        }
                    }
                    if(![listRengContact containsObject:per]){
                        [listRengContact addObject:per];
                    }
                }
                break;
            }
        }
    }
    objAuthen.reengData.listRengContacts = listRengContact;
    [objAuthen.reengData setDidUpdateContact];
}

#pragma mark ham cap nhat danh sach block
-(void)updateReceiverListPhoneBlock:(NSString *)phone_numer idContact:(int)idContact{
    for (Person*per in listAllContact) {
        if(per.idUserContact == idContact){
            for (PhoneNumber * objectPhone in per.listObjectPhone) {
                if([objectPhone.phoneNumber isEqualToString:phone_numer]){
                    objectPhone.phoneIsBlock = 1;
                }
            }
        }
    }
}

#pragma mark ham lay danh sach tat ca contact hien thi len table
-(void)getlistAllContact{
    [listContact removeAllObjects];
    listContact = [Util sortContactBySector:listAllContact];
}

#pragma mark lay danh sach contact reeng hien thi len table
-(void)getListReengContact{
    [listContact removeAllObjects];
    listContact = [Util sortContactBySector :listRengContact];
}

#pragma mark lay danh sach contact yeu thich hien thi len table
-(void)getlistFavoriteContact{
    [listContact removeAllObjects];
    listContact = [Util sortContactBySector :[self getListLike]];
    [self.tableContacts reloadData];
}

#pragma mark ham nhan su kien load lai du lieu khi chua co du lieu trong bang contact
-(void)onInsertContactToDB{
    [self loadDataContact];
}

#pragma mark su kien click vao nut Reeng contact
- (IBAction)actionListReengContacts:(id)sender {
    [self getListReengContact];
    [tableContacts reloadData];
    [btnReengContact setImage:[UIImage imageNamed:@"ic_menu_reeng_press.png" ] forState:UIControlStateNormal];
    [btnContact setImage:[UIImage imageNamed:@"ic_menu_subcontact.png" ] forState:UIControlStateNormal];
    [btnLikeReeng setImage:[UIImage imageNamed:@"ic_menu_favorite.png" ] forState:UIControlStateNormal];
    btnEditContact.enabled = NO;
}

#pragma mark su kien click vao nut all contact
- (IBAction)actionListAllContact:(id)sender {
    [self getlistAllContact];
    [tableContacts reloadData];
    [btnReengContact setImage:[UIImage imageNamed:@"ic_menu_reeng.png" ] forState:UIControlStateNormal];
    [btnContact setImage:[UIImage imageNamed:@"ic_menu_subcontact_press.png" ] forState:UIControlStateNormal];
    [btnLikeReeng setImage:[UIImage imageNamed:@"ic_menu_favorite.png" ] forState:UIControlStateNormal];
    btnEditContact.enabled = YES;

}

#pragma mark su kien click vao nut Like contact
- (IBAction)actionListLikeContact:(id)sender {
    [self getlistFavoriteContact];
//    [tableContacts reloadData];
    [btnReengContact setImage:[UIImage imageNamed:@"ic_menu_reeng.png" ] forState:UIControlStateNormal];
    [btnContact setImage:[UIImage imageNamed:@"ic_menu_subcontact.png" ] forState:UIControlStateNormal];
    [btnLikeReeng setImage:[UIImage imageNamed:@"ic_menu_favorite_press.png" ] forState:UIControlStateNormal];
    btnEditContact.enabled = NO;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (checkHideMenu) {
        checkHideMenu = NO;
        [self hideShowAddOrDeleteMenu];
    }
}

-(void) hideShowAddOrDeleteMenu{
    [UIView animateWithDuration:0.2 animations:^{
        frameMenu.frame=_detailFrameMenu;}];
}

#pragma mark su kien click vao nut Edit contact
- (IBAction)actionEditContact:(id)sender {

    //ic-footer-contact-option-2.png
    checkHideMenu = YES;
    [UIView animateWithDuration:0.2 animations:^{
        frameMenu.frame=CGRectMake(_detailFrameMenu.origin.x, _detailFrameMenu.origin.y- 40.0f, _detailFrameMenu.size.width, _detailFrameMenu.size.height);   }];
}

- (IBAction)actionCancelMenu:(id)sender {
    [self hideShowAddOrDeleteMenu];
}

- (IBAction)btnMenuDeleteClick:(id)sender{
//    [UIView animateWithDuration:0.2 animations:^{
//        frameMenu.frame=_detailFrameMenu;}];
    checkDelete = YES;
    checkHideMenu = YES;

    [UIView animateWithDuration:0.2 animations:^{
        detaiMenuAction.frame=CGRectMake(_detailFrameAction.origin.x, _detailFrameAction.origin.y- 40.0f, _detailFrameAction.size.width, _detailFrameAction.size.height);   }];
    [self.tableContacts reloadData];
}

- (IBAction)btnMenuAddClick:(id)sender{
    [self hideShowAddOrDeleteMenu];
    [self showNewPersonViewController];
}

-(void)showNewPersonViewController
{
	ABNewPersonViewController * pickerNews = [[ABNewPersonViewController alloc] init];
	[pickerNews setNewPersonViewDelegate:self];

    UINavigationController * navControllerAdd = [[UINavigationController alloc] initWithRootViewController:pickerNews];

    [mainViewController presentViewController:navControllerAdd animated:YES completion:nil];

}

#pragma mark add new Contact
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)personNewsRf
{
    Person * objPerson = nil;
    if (personNewsRf !=nil) {
        objPerson = [[Person alloc] init];
        objPerson.listObjectPhone = [[NSMutableArray alloc] init];
        objPerson.firstName = (__bridge_transfer NSString
                               *)ABRecordCopyValue(personNewsRf, kABPersonFirstNameProperty);
        objPerson.lastName =  (__bridge_transfer NSString
                               *)ABRecordCopyValue(personNewsRf, kABPersonLastNameProperty);
        if(objPerson.firstName == nil){
            objPerson.firstName = @"";
        }
        if(objPerson.lastName ==nil){
            objPerson.lastName = @"";
        }

        objPerson.fullName = [NSString stringWithFormat:@"%@ %@",
                              objPerson.firstName, objPerson.lastName];
        NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(personNewsRf)];
        objPerson.idUserContact = [recordId integerValue];

        // get Image
//        if(ABPersonHasImageData(personRef)){
//            objPerson.imgDataAvatar = (__bridge NSData *)ABPersonCopyImageData(personRef);
//            objPerson.imageAvatar = [UIImage imageWithData:sPerson.imgDataAvatar];
//        }

//        if(ABPersonHasImageData(personRef)){
//            if ( &ABPersonCopyImageDataWithFormat != nil ) {
//                // iOS >= 4.1
//                objPerson.imgDataAvatar = (NSData *)CFBridgingRelease(ABPersonCopyImageDataWithFormat(personRef, kABPersonImageFormatThumbnail));
//            } else {
//                // iOS < 4.1
//                objPerson.imgDataAvatar = (NSData *)CFBridgingRelease(ABPersonCopyImageData(personRef));
//            }
//            objPerson.imageAvatar = [UIImage imageWithData:sPerson.imgDataAvatar];
//        }

        ABMultiValueRef pers = ABRecordCopyValue(personNewsRf, kABPersonPhoneProperty);

        for(CFIndex j = 0; j< ABMultiValueGetCount(pers); j++)
        {
            PhoneNumber *phoneNub=[[PhoneNumber  alloc]init];
            NSString *sPhoneNumber = (__bridge NSString*)ABMultiValueCopyValueAtIndex(pers, j);
            phoneNub.phoneNumber = [Util standarFormat:sPhoneNumber];
            if ([DatabaseHelper isCheckViettelNetwork:phoneNub.phoneNumber]) {
                phoneNub.phoneIsViettel=1;
            }
            [objPerson.listObjectPhone addObject:phoneNub];
        }

        [listContact removeAllObjects];
//        dispatch_async(processQueue, ^{@autoreleasepool {
//            @try {
//                if(objPerson.imageAvatar != nil){
//                    objPerson.usr_photoUri = @"";
//                }
//                [DatabaseHelper insertContactUser:objPerson.idUserContact usr_name:objPerson.fullName usr_photoUri:@"" avatarContact:objPerson.imageAvatar usr_isFavorite:0];
//                for (PhoneNumber * objPh in objPerson.listObjectPhone) {
//                    [DatabaseHelper insertPhoneNumber:[NSString stringWithFormat:@"%d",objPerson.idUserContact] phone_number:objPh.phoneNumber phone_user:objPerson.fullName phone_status:@"" phone_avatar_uri:@"" phone_avatar_uri_detail:@"" isViettel:objPh.phoneIsViettel phone_last_change_avatar:@"" isViphone:0 isBlock:0];
//                }
//                idRosterOne = [UtilContactDetail createUUIDSendContact:objAuthen];
//                [UtilContactDetail sendOnePerson:objAuthen idRosterOne:idRosterOne listPhone:objPerson.listObjectPhone];
//            }
//            @catch (NSException *exception) {
//                NSLog(@"Loi %@",exception.name);
//            }
//
//        }});
        [listAllContact addObject:objPerson];
        [self getlistAllContact];
        [objAuthen.reengData setDidUpdateContact];
        [self.tableContacts reloadData];

    }

    [mainViewController dismissModalViewControllerAnimated:YES];

}

#pragma mark ham thuc hien lick button delete o contact
- (IBAction)btnDeleteContactsClick:(id)sender {
    NSString *notifi;
    if(checkSelectAll){
        notifi=[NSString stringWithFormat:@"Bạn có chắn xoá tất cả danh bạ"];
        UIAlertView *aler=[[UIAlertView alloc] initWithTitle:@"Thông báo" message:  @"Bạn có muốn chắc chắn xoá tất cả danh bạ"  delegate:self cancelButtonTitle:@"Đồng ý" otherButtonTitles:@"Huỷ bỏ", nil];
        aler.tag = kAlertViewOneSubMenu;
        [aler show];
    }else{
        if ([listSelected count] > 0) {
            UIAlertView *aler=[[UIAlertView alloc] initWithTitle:@"Thông báo" message: [NSString stringWithFormat:@"Bạn có chắc xoá %d khỏi danh bạ",[listSelected count]]  delegate:self cancelButtonTitle:@"Đồng ý" otherButtonTitles:@"Huỷ bỏ", nil];
            aler.tag = kAlertViewOneSubMenu;
            [aler show];
        }else{
            UIAlertView *aler=[[UIAlertView alloc] initWithTitle:@"Thông báo" message: @"Bạn cần chọn danh bạ để xoá"  delegate:nil cancelButtonTitle:@"Đồng ý" otherButtonTitles:nil, nil];
            [aler show];
        }
    }
 }

// Delete contact from sub menu

#pragma mark ham delete contact from sub menu
-(void)deleteContactSubMenu{
    [UIView animateWithDuration:0.2 animations:^{
        detaiMenuAction.frame=_detailFrameAction;}];
//    [self createAddressBook];
    __block CFErrorRef error = nil;
    if (checkSelectAll) {
        UIAlertView * alertProGressBar = [[UIAlertView alloc] initWithTitle:@"Đang xoá danh bạ ..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];

//        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//
//        indicator.center = CGPointMake(alertProGressBar.bounds.size.width / 2, alertProGressBar.bounds.size.height - 50);
//
//        [alertProGressBar addSubview:indicator];
//        [indicator startAnimating];
        [alertProGressBar show];
        dispatch_async(processQueue, ^{@autoreleasepool {
            for (Person *per in listAllContact) {
                personRef = ABAddressBookGetPersonWithRecordID(addressBook, per.idUserContact);
                ABAddressBookRemoveRecord(addressBook, personRef, &error);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [alertProGressBar dismissWithClickedButtonIndex:0 animated:YES];
                ABAddressBookSave(addressBook, &error);
                // xoa tat ca contact trong db

                [self deleteUserContact];
                checkSelectAll = NO;
                checkDelete = NO;
                [listSelected removeAllObjects];
                [listContact removeAllObjects];
                [listAllContact removeAllObjects];
                [listRengContact removeAllObjects];
                [self.tableContacts reloadData];
                CFRelease(addressBook);
            });
        }});

    }else{
        @try {
            checkSelectAll = NO;
            checkDelete = NO;
            UIAlertView * alertProGressBar = [[UIAlertView alloc] initWithTitle:@"Đang xoá danh bạ ..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];

//            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//
//            indicator.center = CGPointMake(alertProGressBar.bounds.size.width / 2, alertProGressBar.bounds.size.height - 50);
//
//            [alertProGressBar addSubview:indicator];
//            [indicator startAnimating];
            [alertProGressBar show];

            dispatch_async(processQueue, ^{@autoreleasepool {
                for (Person *myPerson in listSelected) {
                    if (myPerson!= nil && addressBook != nil) {
                        personRef = ABAddressBookGetPersonWithRecordID(addressBook, myPerson.idUserContact);
                        ABAddressBookRemoveRecord(addressBook, personRef, &error);
                        @try {
                            [DatabaseHelper deleteContactUser:myPerson.idUserContact];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"Loi khong delete dc db");
                        }
                        [listAllContact removeObject:myPerson];
                        if([listRengContact containsObject:myPerson]){
                        [listRengContact removeObject:myPerson];
                        }
                    }
                }
            dispatch_async(dispatch_get_main_queue(), ^{
                [alertProGressBar dismissWithClickedButtonIndex:0 animated:YES];
                ABAddressBookSave(addressBook, &error);
                [listSelected removeAllObjects];
                [listContact removeAllObjects];
                [self getlistAllContact];
                [self.tableContacts reloadData];
                CFRelease(addressBook);
            });
            }});
        }
        @catch (NSException *exception) {
            NSLog(@"XXX Loi %@",exception.name);
        }

    }
}

#pragma mark ham xoa nhieu dl trong db
-(void) deleteUserContact{
    @try {
        [DatabaseHelper deleteAllRowUserContact];
        [DatabaseHelper deleteAllRowPhoneNumber];
    }
    @catch (NSException *exception) {
        NSLog(@"Delete Fail");
    }
}

#pragma mark su kien click tu alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (alertView.tag) {
        case kAlertViewOneSubMenu:
        {
            switch (buttonIndex) {
                case 0:
                    [self deleteContactSubMenu];
                    break;

                default:
                    break;
            }
        }
            break;
        case kAlertViewTwoActionSheet:
        {
            switch (buttonIndex) {
                case 0:
                    [self deleteOneActionSheet];
                    break;

                default:
                    break;
            }
        }
            break;

        default:
            break;
    }
}

#pragma mark button cancel cua sun menu delete
- (IBAction)btnCancelClick:(id)sender {
    [UIView animateWithDuration:0.2 animations:^{
        detaiMenuAction.frame=_detailFrameAction;}];
    checkDelete = NO;
    checkSelectAll = NO;
    checkHideMenu = YES;
    [btnCheck setImage:[UIImage imageNamed:@"ic_icon_ok_black.png"] forState:UIControlStateNormal] ;
    [listSelected removeAllObjects];
    [self.tableContacts reloadData];
}

#pragma mark su kien click cua nut tat ca
- (IBAction)btnCheckClick:(id)sender {
    checkDelete = YES;
    if(!checkSelectAll)
    {
        [btnCheck setImage:[UIImage imageNamed:@"ic_icon_sent_ok.png"] forState:UIControlStateNormal] ;
        checkSelectAll = YES;
        [listSelected removeAllObjects];
        for (Person * myPer in listAllContact) {
            [listSelected addObject:myPer];
        }

    }
    else{
        [btnCheck setImage:[UIImage imageNamed:@"ic_icon_ok_black.png"] forState:UIControlStateNormal] ;
        checkSelectAll = NO;
        [listSelected removeAllObjects];
    }
    [self.tableContacts reloadData];
}

#pragma mark ham hien thi block or unblock
-(NSString *) checkUserBlockOrUnBlock :(NSMutableArray *) listObjectPhone{
    NSString *  strBlock;
    for (PhoneNumber * phoneObject in listObjectPhone) {
        if(phoneObject.phoneIsBlock == 1){
            strBlock = @"Unblock";
            break;
        }else{
            strBlock = @"Block";
        }
    }
    return strBlock;
}

#pragma mark su kien long click
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p;
    ContactTableCell *cell;
  if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
    if (isFinter) {
        p = [gestureRecognizer locationInView:self.searchDisplayController.searchResultsTableView];
        indexDelete = [self.searchDisplayController.searchResultsTableView indexPathForRowAtPoint:p];
        cell = (ContactTableCell*)[self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexDelete];
        sPerson = [filteredTableData objectAtIndex:indexDelete.row] ;

    }else
    {
        p = [gestureRecognizer locationInView:tableContacts];
        indexDelete = [tableContacts indexPathForRowAtPoint:p];
        cell = (ContactTableCell*)[tableContacts cellForRowAtIndexPath:indexDelete];
        sPerson = [[listContact objectAtIndex:indexDelete.section] objectAtIndex:indexDelete.row];
    }

        CGPoint p = [gestureRecognizer locationInView:tableContacts];
        indexDelete = [tableContacts indexPathForRowAtPoint:p];
        if (indexDelete == nil)
            NSLog(@"long press on table view but not on a row");
        else{

            ContactTableCell *cell = (ContactTableCell*)[tableContacts cellForRowAtIndexPath:indexDelete];
            sPerson = [[listContact objectAtIndex:indexDelete.section] objectAtIndex:indexDelete.row];
            strName = cell.name.text;

            _y=42;
            _x=10;

            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                     delegate:self
                                                            cancelButtonTitle:nil
                                                       destructiveButtonTitle:nil
                                                            otherButtonTitles:nil];
            aac = actionSheet;

            UIImageView *background = [[UIImageView alloc] init];
            [background setBackgroundColor:[UIColor colorWithRed:217/255.0f green:221/255.0f blue:230/255.0f alpha:1.0f]];
            [background setFrame:CGRectMake(0, 0, 320, 580)];
            background.contentMode = UIViewContentModeScaleToFill;
            [aac addSubview:background];

            //add name
            UIButton * name = [self initbuttonName:strName nameImager:nil  x:0 y:0 width:320   height:55 State:2];
            [aac addSubview:name];

            //button goi thuong
            UIButton * btnCallNone=[self initbuttonName:@"Gọi thường" nameImager:nil x:_x y:(_y ) width:(300) height:40 State:0];
            btnCallNone.tag = 1;
            [btnCallNone addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
            [aac addSubview:btnCallNone];

            //button goi reeang
            UIButton * btnCallIP=[self initbuttonName:@"Gọi IP-GSM" nameImager:nil x:_x y:(_y +50) width:(300) height:40 State:0];
            btnCallIP.tag = 2;
            [btnCallIP addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
            [aac addSubview:btnCallIP];

            //button Chat
            UIButton * btnChat=[self initbuttonName:@"Chat" nameImager:nil x:_x y:(_y +100) width:(300) height:40 State:0];
            btnChat.tag = 3;
            [btnChat addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
            [aac addSubview:btnChat];

            //button block/unlock

            NSString * strPhoneLock = [self checkUserBlockOrUnBlock:sPerson.listObjectPhone];
            UIButton * btnBlock =[self initbuttonName:strPhoneLock nameImager:nil x:_x y:(_y +150) width:(300) height:40 State:0];
            btnBlock.tag = 4;
            [btnBlock addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
            [aac addSubview:btnBlock];

//            //button sua
//            UIButton * sua =[self initbuttonName:@"Edit" nameImager:nil x:_x y:(_y ) width:(300) height:40 State:0];
//            callNone.tag = 5;
//            [callNone addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
//            [aac addSubview:sua];
//
//            //button xoa
//            UIButton * delete =[self initbuttonName:@"Delete" nameImager:nil x:_x y:(_y ) width:(300) height:40 State:0];
//            callNone.tag = 6;
//            [callNone addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
//            [aac addSubview:delete];

            //button cance
            UIButton * btnCancelActionSheet =[self initbuttonName:@"Cancel" nameImager:nil x:_x y:(_y+200) width:(300) height:40 State:1];
            btnCancelActionSheet.tag = 5;
            [btnCancelActionSheet addTarget:self action:@selector(btnClick:)    forControlEvents:UIControlEventTouchUpInside];
            [aac addSubview:btnCancelActionSheet];

            [aac showInView:mainViewController.view];
            [aac setBounds:CGRectMake(0,0,320, 580)];

        }
    }

}

#pragma mark ham mau cua button
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark create button ActionSheet
-(UIButton* )initbuttonName:(NSString *)name nameImager:(NSString *)nameImager x:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h State:(int) state
{
    //set background
    UIImage *image=[self imageWithColor:[UIColor colorWithRed:50/255.0f green:11/255.0f blue:102/255.0f alpha:1.0f]];

    UIButton *btn= [UIButton buttonWithType: UIButtonTypeCustom];

    btn.frame = CGRectMake(x, y, w, h);

    [btn setTitle:name forState:UIControlStateNormal];

    btn.titleLabel.textAlignment = NSTextAlignmentCenter;
    btn.adjustsImageWhenHighlighted = YES;
    switch (state) {
        case 1:
            //[btn setBackgroundImage:image forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor colorWithRed:255/255.0f green:1/255.0f blue:1/255.0f alpha:1.0f]];

            [btn setTitleColor:[UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithRed:0/255.0f green:177/255.0f blue:148/255.0f alpha:1.0f] forState:UIControlStateHighlighted];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.layer.cornerRadius = 7.0;
            btn.layer.borderWidth = 1.0;
            btn.layer.borderColor = [UIColor darkGrayColor].CGColor;
            btn.clipsToBounds = YES;
            break;
        case 2:
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.titleLabel.font = [UIFont fontWithName:@"System" size: 30];
            btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            [btn setTitleColor:[UIColor colorWithWhite:0.0f alpha:1.0f] forState:UIControlStateNormal];
            break;
        case 0:
            [btn setBackgroundImage:image forState:UIControlStateNormal];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            [btn setTitleColor:[UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithRed:0/255.0f green:177/255.0f blue:148/255.0f alpha:1.0f] forState:UIControlStateHighlighted];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.layer.cornerRadius = 7.0;
            btn.layer.borderWidth = 1.0;
            btn.layer.borderColor = [UIColor darkGrayColor].CGColor;
            btn.clipsToBounds = YES;
            break;
    }
    return btn;
}

#pragma mark create line cho AacSheet
-(UIImageView*) initnameX:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h
{

    UIImageView *line=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"l_border_menu.png"]];
    [line setFrame:CGRectMake(x, y, w, h)];
    return line;
}

-(ABAddressBookRef) createAddressBook
{
    addressBook = nil;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) {
        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    }else{
        addressBook = ABAddressBookCreate();
    }
    return addressBook;
}

#pragma mark ham kiem tra do co mot hay nhieu so dt
-(BOOL *) checkMorePhoneNumber :(NSMutableArray *) listObjectPhone{

    if([listObjectPhone count] > 1){
        isPhoneCountMore = TRUE;
    }else{
        isPhoneCountMore = FALSE;
    }
    return &(isPhoneCountMore);
}

#pragma mark lay ve so dien thoai cua nguoi dung
-(NSString *) stringMyPhone :(NSMutableArray * )listObjectPhone{
    NSString * phoneString;
    for (PhoneNumber * phoneObject in listObjectPhone) {
        phoneString = phoneObject.phoneNumber;
    }
    return phoneString;
}

#pragma mark ham thuc hien phuong thuc goi
-(void) functinMyCallLongClick : (NSString *) strTitile{
    NSString *phoneLinkString = [NSString stringWithFormat:@"tel:%@", strTitile];
    NSURL *phoneLinkURL = [NSURL URLWithString:phoneLinkString];
    [[UIApplication sharedApplication] openURL:phoneLinkURL];
}

#pragma ham thuc hien goi phuong thuc chat
-(void) functionMyChatLongClick : (NSString *) strTitile{
    chatViewDetail = [[ChatViewDetail alloc]init];
    chatViewDetail.mainView = mainViewController;
    chatViewDetail.thread_id = [Util checkExitThread:strTitile];
    chatViewDetail.thread_name = strTitile;
    chatViewDetail.thread_type = @"0";
    [Util showNextView:mainViewController.view :chatViewDetail.view];
}

#pragma mark thiet ke moi
-(void)btnClick:(id)sender{

    UIButton *btnSelected = (UIButton*)sender;
    NSString * phoneLongClick = [self stringMyPhone:sPerson.listObjectPhone];
    switch (btnSelected.tag) {

        case 1:
        {
            [aac dismissWithClickedButtonIndex:0 animated:YES];
            [self functinMyCallLongClick:phoneLongClick];
        }
            break;
        case 2:
        {
            [aac dismissWithClickedButtonIndex:0 animated:YES];
            UIAlertView *alerIPGSM=[[UIAlertView alloc] initWithTitle:@"Thông báo" message: @"Hiện chức năng gọi IP-GSM chưa được hỗ trợ vui lòng thử lại sau"  delegate:nil cancelButtonTitle:@"Đồng ý" otherButtonTitles:nil, nil];
            [alerIPGSM show];
        }
            break;
        case 3:
        {
            [aac dismissWithClickedButtonIndex:0 animated:YES];
            [self functionMyChatLongClick:phoneLongClick];
        }
            break;
        case 4:
        {
            [aac dismissWithClickedButtonIndex:0 animated:YES];
            [self blockPhoneNumber:sPerson.listObjectPhone];
        }
            break;
        case 5:
        {
            [aac dismissWithClickedButtonIndex:0 animated:YES];
        }
            break;
    }

}

#pragma mark thiet ke cu
//-(void)btnClick:(id)sender{
//
//    UIButton *btnSelected = (UIButton*)sender;
//    NSString*name = btnSelected.titleLabel.text;
//    NSString * phoneLongClick = [self stringMyPhone:sPerson.listObjectPhone];
//    if ([name isEqualToString:@"Gọi thường"]) {
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//        [self functinMyCallLongClick:phoneLongClick];
//    }
//    if ([name isEqualToString:@"Gọi IP-GSM"]) {
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//        [self functinMyCallLongClick:phoneLongClick];
//    }
//    if ([name isEqualToString:@"Chat"]) {
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//        [self functionMyChatLongClick:phoneLongClick];
//    }
//    if ([name isEqualToString:@"Block/Unblock"]) {
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//        [self blockPhoneNumber:sPerson.listObjectPhone];
//        NSLog(@"Block/Unblock");
//    }
//    if ([name isEqualToString:@"Edit"]) {
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//        [self showPersonViewController];
//    }
//    if ([name isEqualToString:@"Delete"]) {
//
//        UIAlertView *aler=[[UIAlertView alloc] initWithTitle:@"Thông báo" message: [NSString stringWithFormat:@"Bạn có muốn chắc chắn xoá %@ trong danh bạ",sPerson.fullName]  delegate:self cancelButtonTitle:@"Đồng ý" otherButtonTitles:@"Huỷ bỏ", nil];
//        aler.tag = kAlertViewTwoActionSheet;
//        [aler show];
//
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//
//    }
//    if ([name isEqualToString:@"Cancel"]) {
//        NSLog(@"Cancel");
//        [aac dismissWithClickedButtonIndex:0 animated:YES];
//    }
//}

#pragma mark ham xoa mot contact tu ActionSheet
-(void)deleteOneActionSheet{
    CFErrorRef error = nil;
//    [self createAddressBook];
    if(addressBook != nil){
        personRef = ABAddressBookGetPersonWithRecordID(addressBook, sPerson.idUserContact);
        ABAddressBookRemoveRecord(addressBook, personRef, &error);
        ABAddressBookSave(addressBook, &error);

        @try {
            [DatabaseHelper deleteContactUser:sPerson.idUserContact];
        }
        @catch (NSException *exception) {
            NSLog(@"Loi khong delete dc db");
        }

        [[listContact objectAtIndex:indexDelete.section] removeObjectAtIndex:indexDelete.row];
        [listAllContact removeObject:sPerson];
        if([listRengContact containsObject:sPerson]){
            [listRengContact removeObject:sPerson];
        }
        [self.tableContacts reloadData];
    }
}

#pragma mark ham thuc hien block phone
-(void) blockPhoneNumber : (NSMutableArray *) listPhone{
    dispatch_async(processQueue, ^{@autoreleasepool {
        int isBlock = 0;
        for (PhoneNumber * objectPhone in listPhone) {
            if(objectPhone.phoneIsBlock == 1){
                isBlock = 1;
                break;
            }
        }
        if(isBlock == 1){
            [UtilContactDetail sendPhoneUnLock:objAuthen listPhone:listPhone];
            @try {
                for (PhoneNumber * objectPhone in listPhone) {
                    objectPhone.phoneIsBlock = 0;
                    [DatabaseHelper updatePhoneBlock:objectPhone.phoneNumber is_block:0];
                }
            }
            @catch (NSException *exception) {
                NSLog(@"Loi update %@ ",exception.name);
            }
            NSLog(@"Thuc hien Unblock");
            // Thuc hien Unblock
        }else{
            [UtilContactDetail sendPhoneBlock:objAuthen listPhone:listPhone];
            @try {
                for (PhoneNumber * objectPhone in listPhone) {
                    objectPhone.phoneIsBlock = 1;
                    [DatabaseHelper updatePhoneBlock:objectPhone.phoneNumber is_block:1];
                }
            }
            @catch (NSException *exception) {
                NSLog(@"Loi update %@ ",exception.name);
            }
            NSLog(@"Thuc hien Block");
            // Thuc hien Block
        }
    }});
}

-(void)showPersonViewController
{
    personRef = ABAddressBookGetPersonWithRecordID([self createAddressBook], sPerson.idUserContact);

    if ((personRef != nil))
    {

        picker = [[ABPersonViewController alloc] init];
        [picker setPersonViewDelegate:self];

        picker.displayedPerson = personRef;
        picker.title=strName;
        UIBarButtonItem* doneButton  = [[UIBarButtonItem alloc]
                                        initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                        target:self
                                        action:@selector(actionSave:)];
        UIBarButtonItem *cancelButton= [[UIBarButtonItem alloc]
                                        initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                        target: self
                                        action: @selector(returnFromPersonView)];
        picker.editing=YES;
        picker.allowsEditing = YES;

        navController = [[UINavigationController alloc]initWithRootViewController:picker];

        [mainViewController presentModalViewController:navController animated:YES];

        self.defaultRightBarButtonItem = picker.navigationItem.rightBarButtonItem;
        NSLog(@"%@",defaultRightBarButtonItem.title);

        picker.navigationItem.rightBarButtonItem=doneButton;
        picker.navigationItem.leftBarButtonItem=cancelButton;
    }
    else
    {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Thông báo"
                                                        message:[NSString stringWithFormat:@"Không thể tìm thấy danh bạ cần xoá"]
                                                       delegate:nil
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark action
-(void)returnFromPersonView
{
    [tableContacts reloadData];
    [mainViewController dismissModalViewControllerAnimated:YES];
}

- (void)actionSave:(UIBarButtonItem *)sender {
    /// #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self.defaultRightBarButtonItem.target
     performSelector:self.defaultRightBarButtonItem.action
     withObject:self.defaultRightBarButtonItem.target];
    NSString *firstName = (__bridge_transfer NSString
                           *)ABRecordCopyValue(personRef, kABPersonFirstNameProperty);
    NSString *lastName =  (__bridge_transfer NSString
                           *)ABRecordCopyValue(personRef, kABPersonLastNameProperty);
    if(firstName == nil){
        firstName = @"";
    }
    if(lastName ==nil){
        lastName = @"";
    }

    sPerson.fullName = [NSString stringWithFormat:@"%@ %@",firstName, lastName];
    NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(personRef)];

    ABMultiValueRef phones = ABRecordCopyValue(personRef, kABPersonPhoneProperty);

    [sPerson.listObjectPhone removeAllObjects];

    // get Image
    if(ABPersonHasImageData(personRef)){
        if ( &ABPersonCopyImageDataWithFormat != nil ) {
            // iOS >= 4.1
            sPerson.imgDataAvatar = (NSData *)CFBridgingRelease(ABPersonCopyImageDataWithFormat(personRef, kABPersonImageFormatThumbnail));
        } else {
            // iOS < 4.1
            sPerson.imgDataAvatar = (NSData *)CFBridgingRelease(ABPersonCopyImageData(personRef));
        }
        sPerson.imageAvatar = [UIImage imageWithData:sPerson.imgDataAvatar];
    }

    for(CFIndex j = 0; j< ABMultiValueGetCount(phones); j++)
    {
        PhoneNumber *phoneNub=[[PhoneNumber  alloc]init];
        NSString *sPhoneNumber = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j);
        phoneNub.phoneNumber = [Util standarFormat:sPhoneNumber];
        if ([DatabaseHelper isCheckViettelNetwork:phoneNub.phoneNumber]) {
            phoneNub.phoneIsViettel = 1;
        }
        [sPerson.listObjectPhone addObject:phoneNub];
    }

    dispatch_async(processQueue, ^{@autoreleasepool {
        @try {
            if(sPerson.imageAvatar != nil){
                sPerson.usr_photoUri = @"";
            }
            [DatabaseHelper updateEditUserContact:[recordId integerValue] usr_name:sPerson.fullName usr_photoUri:sPerson.usr_photoUri avatarContact:sPerson.imageAvatar];
            [DatabaseHelper addPhoneEditContact:sPerson.listObjectPhone idContact:[recordId integerValue]];
            [UtilContactDetail sendOnePerson:objAuthen idRosterOne:[UtilContactDetail createUUIDSendContact:objAuthen] listPhone:sPerson.listObjectPhone];
        }
        @catch (NSException *exception) {
            NSLog(@"Loi %@",exception.name);
        }

    }});
    [objAuthen.reengData setDidUpdateContact];
    [self.tableContacts reloadData];

    [mainViewController dismissModalViewControllerAnimated:YES];

}

- (void)dismissPersonViewController
{
    [picker dismissModalViewControllerAnimated:YES];
}
#pragma mark delegate edit person
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
    return YES;
}

void MyAddressBookExternalChangeCallback (ABAddressBookRef notifyAddressBook,CFDictionaryRef info,void *context)
{
    NSLog(@"in MyAddressBook External Change Callback");
    // Du lieu da thay doi
    ContactViewController * viewContact = (__bridge ContactViewController *)(context);
    [viewContact updateContactWhenUserChange];
}

-(void)updateContactWhenUserChange {
    [indicatoView startAnimating];

    dispatch_async(processQueue, ^{ @autoreleasepool {

        listContactDB = [[NSMutableArray alloc]init];
        listContactDB = [Util getPersonOutOfAddressBookNonSort];

        for (Person * myPerPhone in listContactDB) {
            for (Person * myPerDB in listAllContact) {
//                NSLog(@" myPerPhone  %@  va id %d ",myPerPhone.fullName, myPerPhone.idUserContact);
//                NSLog(@" myPerDB  %@  va id %d ",myPerDB.fullName, myPerDB.idUserContact);
                if(myPerPhone.idUserContact == myPerDB.idUserContact){
                    myPerPhone.isUpdate = TRUE;
                    myPerDB.isUpdate = TRUE;
//                    NSLog(@" myPerPhone  %@  va id %d ",myPerPhone.fullName, myPerPhone.idUserContact);
//                    NSLog(@" myPerDB  %@  va id %d ",myPerDB.fullName, myPerDB.idUserContact);
                    [DatabaseHelper updateEditUserContact:myPerDB.idUserContact usr_name:myPerPhone.fullName usr_photoUri:myPerPhone.usr_photoUri avatarContact:myPerPhone.imageAvatar];
                    [DatabaseHelper addPhoneEditContact:myPerPhone.listObjectPhone  idContact:myPerPhone.idUserContact];
                    break;
                }
            }
        }

        for (Person * perAdd in listContactDB) {
            if(!perAdd.isUpdate){
                [DatabaseHelper insertContactUser:perAdd.idUserContact usr_name:perAdd.fullName usr_photoUri:@"" avatarContact:perAdd.imageAvatar usr_isFavorite:0];
                if([perAdd.listObjectPhone count] > 0){
                    for (PhoneNumber * myPhone in perAdd.listObjectPhone) {
                        [DatabaseHelper insertPhoneNumber:[NSString stringWithFormat:@"%d",perAdd.idUserContact] phone_number:myPhone.phoneNumber phone_user:perAdd.fullName phone_status:@"" phone_avatar_uri:@"" phone_avatar_uri_detail:@"" isViettel:myPhone.phoneIsViettel phone_last_change_avatar:@"" isViphone:0 isBlock:0];
                    }
                }

            }

        }

        for (Person * perDelete in listAllContact) {
            if(!perDelete.isUpdate){
                [DatabaseHelper deleteContactUser:perDelete.idUserContact];
            }
        }
        [self flushCache];
        [self clearAllData];
        dispatch_async(dispatch_get_main_queue(), ^{ @autoreleasepool{
            [self loadDataContact];
            [indicatoView stopAnimating];
        }});
    }});
}

-(void) clearAllData{
    [listAllContact removeAllObjects];
    [listRengContact removeAllObjects];
    [listSelected removeAllObjects];
    [listContact removeAllObjects];
    [tmpReengFirst removeAllObjects];
    [filteredTableData removeAllObjects];
}

- (void)viewDidUnload {
    ABAddressBookUnregisterExternalChangeCallback(addressBook, MyAddressBookExternalChangeCallback, (__bridge void *)(self));
    [self setBtnReengContact:nil];
    [self setBtnContact:nil];
    [self setBtnLikeReeng:nil];
    [self setBtnEditContact:nil];
    [self setBtnDeleteContact:nil];
    [self setBtnCheck:nil];
    [self setBtnCancel:nil];
    CFRelease(addressBook);
    [objAuthen.messageParser removeDelegate:self];
    [objAuthen.reengData removeDelegate:self];
    filteredTableData = nil;
    listSelected = nil;
    sPerson = nil;
    listRengContact = nil;
    tmpReengFirst = nil;
    [super viewDidUnload];
}

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.Widgets.Models;
using OrchardCore.Widgets.ViewModels;

namespace OrchardCore.Widgets.Controllers
{
    public class AdminController : Controller
    {
        private readonly IContentManager _contentManager;
        private readonly IContentItemDisplayManager _contentItemDisplayManager;
        private readonly IShapeFactory _shapeFactory;
        private readonly IUpdateModelAccessor _updateModelAccessor;

        public AdminController(
            IContentManager contentManager,
            IContentItemDisplayManager contentItemDisplayManager,
            IShapeFactory shapeFactory,
            IUpdateModelAccessor updateModelAccessor)
        {
            _contentItemDisplayManager = contentItemDisplayManager;
            _contentManager = contentManager;
            _shapeFactory = shapeFactory;
            _updateModelAccessor = updateModelAccessor;
        }

        public async Task<IActionResult> BuildEditor(string id, string prefix, string prefixesName, string contentTypesName, string contentItemsName, string zonesName, string zone, string targetId, string parentContentType, string partName)
        {
            if (String.IsNullOrWhiteSpace(id))
            {
                return NotFound();
            }

            var contentItem = await _contentManager.NewAsync(id);

            contentItem.Weld(new WidgetMetadata());

            string cardCollectionType = nameof(WidgetsListPart);

            //Create a Card Shape
            dynamic contentCard = await _shapeFactory.New.ContentCard(
                //Updater is the controller for AJAX Requests
                Updater: _updateModelAccessor.ModelUpdater,
                //Shape Specific
                CollectionShapeType: cardCollectionType,
                ContentItem: contentItem,
                BuildEditor: true,
                ParentContentType: parentContentType,
                CollectionPartName: partName,
                //WidgetListPart Specific
                ZoneValue: zone,
                //Card Specific Properties
                TargetId: targetId,
                Inline: true,
                CanMove: true,
                CanDelete: true,
                //Input hidden
                //Prefixes
                PrefixValue: prefix,
                PrefixesId: prefixesName.Replace('.', '_'),
                PrefixesName: prefixesName,
                //ContentTypes
                ContentTypesId: contentTypesName.Replace('.', '_'),
                ContentTypesName: contentTypesName,
                //ContentItems
                ContentItemsId: contentItemsName.Replace('.', '_'),
                ContentItemsName: contentItemsName,
                //Zones
                ZonesId: zonesName.Replace('.', '_'),
                ZonesName: zonesName
            );

            var model = new BuildEditorViewModel
            {
                EditorShape = contentCard
            };

            return View("Display", model);
        }
    }
}


text:
package com.smoketurner.graphiak.managed;

import java.util.Objects;
import javax.annotation.Nonnull;
import io.dropwizard.lifecycle.Managed;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.FastThreadLocal;

public class ChannelFutureManager implements Managed {

    private final ChannelFuture future;

    /**
     * Constructor
     *
     * @param future
     *            ChannelFuture to manage
     */
    public ChannelFutureManager(@Nonnull final ChannelFuture future) {
        this.future = Objects.requireNonNull(future);
    }

    @Override
    public void start() throws Exception {
        future.sync();
    }

    @Override
    public void stop() throws Exception {
        future.channel().closeFuture();
        // clean up internal Netty threads
        FastThreadLocal.removeAll();
        FastThreadLocal.destroy();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!--

    Copyright 2005-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
  <bean id="TravelAccountExtension" parent="TravelAccountExtension-parentBean"/>

  <bean id="TravelAccountExtension-parentBean" abstract="true" parent="BusinessObjectEntry">
    <property name="businessObjectClass" value="org.kuali.rice.krad.demo.travel.account.TravelAccountExtension"/>
    <property name="titleAttribute" value="number"/>
    <property name="attributes">
      <list>
        <ref bean="TravelAccountExtension-number"/>
        <ref bean="TravelAccountExtension-accountTypeCode"/>
      </list>
    </property>
    <property name="objectLabel" value="Travel Account Extension"/>
  </bean>

  <!-- Attribute Definitions -->

  <bean id="TravelAccountExtension-number" parent="TravelAccountExtension-number-parentBean"/>
  <bean id="TravelAccountExtension-number-parentBean" abstract="true" parent="TravelAccount-number">
  </bean>

  <bean id="TravelAccountExtension-accountTypeCode" parent="TravelAccountExtension-accountTypeCode-parentBean"/>
  <bean id="TravelAccountExtension-accountTypeCode-parentBean" abstract="true" parent="TravelAccountType-accountTypeCode">
  </bean>
</beans>


text:
class CORE_API GPUQuery
{
public:
    static const GLint   queryi(const GLenum penum);
    static const QString querys(const GLenum penum);
    static const QString glew  (const GLenum penum);

    static const QString vendor();
    static const QString renderer();
    static const QString version();
    static const QString glewVersion();

    static const bool isCoreProfile();

    // Checks for an opengl error and prints to console if one occurred
    static const bool error(
        const char * file
    ,   const int line);

    static const QString glewError(const GLenum penum);

    // Extension Info

    static const bool extensionSupported(const char * extension);
    static const bool extensionSupported(const QString & extension);

    // Memory Info (return -1 if query is not possible or failed)

    static const GLint totalMemory();
    static const GLint dedicatedMemory();
    static const GLint availableMemory();
    static const GLint evictionCount();
    static const GLint evictedMemory();

protected:
    static const GLint memoryInfo(const GLenum penum);
};

#define glError() GPUQuery::error(__FILE__, __LINE__)
#define glIsError() GPUQuery::error(__FILE__, __LINE__)