package com.example.listviewcustom05;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbAdapter 
{

	// public static final String KEY_ROWID = "_id";
	// public static final String KEY_CODE = "code";
	// public static final String KEY_NAME = "name";
	// public static final String KEY_CONTINENT = "continent";
	// public static final String KEY_REGION = "region";
	 
 
	 public static final String KEY_ROWID = "_id";
	 public static final String KEY_NOM = "nom";
	 public static final String KEY_PRENOM = "prenom";
	 public static final String KEY_ADRESSE = "adresse";
	 public static final String KEY_EMAIL = "email";
	 public static final String KEY_PORTABLE = "portable";
	 public static final String KEY_FIXE = "fixe";
	 public static final String KEY_PHOTOGRAPH = "photograph";
	 
	 //private String[] columns= {KEY_ROWID, KEY_NOM, KEY_PRENOM, KEY_ADRESSE, KEY_EMAIL, KEY_PORTABLE, KEY_FIXE, KEY_PHOTOGRAPH};
	

	 private static final String TAG = "ContactsDbAdapter";
	 private DatabaseHelper mDbHelper;
	 private SQLiteDatabase mDb;

	 private static final String DATABASE_NAME = "pat06";
	 private static final String SQLITE_TABLE = "contact";
	 private static final int DATABASE_VERSION = 1;

	 private final Context mCtx;

	/* 
	 private static final String DATABASE_CREATE =
	  "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
	  KEY_ROWID + " integer PRIMARY KEY autoincrement," +
	  KEY_CODE + "," +
	  KEY_NAME + "," +
	  KEY_CONTINENT + "," +
	  KEY_REGION + "," +
	  " UNIQUE (" + KEY_CODE +"));";
	*/ 
	 
	 private static final String DATABASE_CREATE =
			  "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
					  KEY_ROWID + " integer PRIMARY KEY autoincrement," +
					  KEY_NOM + "," +
					  KEY_PRENOM + "," +
					  KEY_ADRESSE + "," +
					  KEY_EMAIL + "," +
					  KEY_PORTABLE + "," +
					  KEY_FIXE + "," +
					  KEY_PHOTOGRAPH  +  " ); " ;

		 private static class DatabaseHelper extends SQLiteOpenHelper 
		 {
		
				  DatabaseHelper(Context context)
				  {
				   super(context, DATABASE_NAME, null, DATABASE_VERSION);
				  }
		
		
				  @Override
				  public void onCreate(SQLiteDatabase db)
				  {
					  Log.w(TAG, DATABASE_CREATE);
					  db.execSQL(DATABASE_CREATE);
				  }
		
				  @Override
				  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
				  {
					   Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					     + newVersion + ", which will destroy all old data");
					   db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
					   onCreate(db);
				  }
		 }

		 public DbAdapter(Context ctx)
		 {
			this.mCtx = ctx;
		 }

		 public DbAdapter open() throws SQLException 
		 {
			 mDbHelper = new DatabaseHelper(mCtx);
			 mDb = mDbHelper.getWritableDatabase();
			 return this;
		 }

		 public void close()
		 {
			 if(mDbHelper != null)
			 {
				 mDbHelper.close();
			 }
		 }
 
 
public int getContactsCount() 
{
        //String countQuery = "SELECT  * FROM " + SQLITE_TABLE;
        //Cursor cursor = mDb.rawQuery(countQuery, null);
        //cursor.close();
        //return cursor.getCount();
        
        
        
      
		 
		 
		 Cursor c = mDb.rawQuery("select * from contact",null);
		 Log.i("Number of Records"," :: "+c.getCount());
		 
	     
		 return(c.getCount());
		 
	     //int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_CONTACT);
	     ///return numRows;
	     
	     //return c.getCount();
	     
	     //cursor.close();
	     //int q = cursor.getCount();
	     //return cursor.getCount();
        
}

public Cursor query(String champ1, String val1, String champ2, String val2)
{
		String query = "Select * FROM " + SQLITE_TABLE + " WHERE " + champ1 + " =  \"" + val1 + "\"" + " AND " + champ2 + " =  \"" + val2  + "\"";
		
		return mDb.rawQuery(query, null);
		
		//Cursor provicursor = mDb.rawQuery(query, null);
		//provicursor.moveToFirst();
		//String index = provicursor.getString(provicursor.getColumnIndex("fixe"));
		//String ex = cursor.getString(cursor.getColumnIndex("_id"));
		//String item = cursor.getString(cursor.getColumnIndex(KEY_ROWID));
		//Integer item = cursor.getInt(cursor.getColumnIndex(KEY_ROWID));
		
		//int item = 64;
		
		//String index = "4";
		
		
}

public long createContact(String nom, String prenom, String adresse, String email, String portable, String fixe, String photograph ) 
{
		  ContentValues initialValues = new ContentValues();
		  initialValues.put(KEY_NOM, nom);
		  initialValues.put(KEY_PRENOM, prenom);
		  initialValues.put(KEY_ADRESSE, adresse);
		  initialValues.put(KEY_EMAIL, email);
		  initialValues.put(KEY_PORTABLE, portable);
		  initialValues.put(KEY_FIXE, fixe);
		  initialValues.put(KEY_PHOTOGRAPH, photograph);
		  
		  return mDb.insert(SQLITE_TABLE, null, initialValues);
		  
}
/*
public long createContact(String code, String name, String continent, String region) 
{
		  ContentValues initialValues = new ContentValues();
		  initialValues.put(KEY_CODE, code);
		  initialValues.put(KEY_NAME, name);
		  initialValues.put(KEY_CONTINENT, continent);
		  initialValues.put(KEY_REGION, region);
		  return mDb.insert(SQLITE_TABLE, null, initialValues);
}
*/
public boolean deleteAllCountries()
{
		  int doneDelete = 0;
		  doneDelete = mDb.delete(SQLITE_TABLE, null , null);
		  Log.w(TAG, Integer.toString(doneDelete));
		  return doneDelete > 0;
 }
/*
 public Cursor fetchCountriesByName(String inputText) throws SQLException 
 {
		  Log.w(TAG, inputText);
		  Cursor mCursor = null;
		  if (inputText == null  ||  inputText.length () == 0)  {
		   mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
		     KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, 
		     null, null, null, null, null);
		
		  }
		  else {
		   mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
		     KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, 
		     KEY_NAME + " like '%" + inputText + "%'", null,
		     null, null, null, null);
		  }
		  if (mCursor != null) {
		   mCursor.moveToFirst();
		  }
		  return mCursor;

 }
*/


public Cursor fetchContactByName(String inputText) throws SQLException 
{
		  Log.w(TAG, inputText);
		  Cursor mCursor = null;
		  if (inputText == null  ||  inputText.length () == 0) 
		  {
			  mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, KEY_NOM, KEY_PRENOM, KEY_ADRESSE, KEY_EMAIL, KEY_PORTABLE, KEY_FIXE , KEY_PHOTOGRAPH }, 
		     null, null, null, null, null);
		  }
		  
		  else 
		  {
			  mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID, KEY_NOM, KEY_PRENOM, KEY_ADRESSE, KEY_EMAIL, KEY_PORTABLE, KEY_FIXE , KEY_PHOTOGRAPH}, 
		     KEY_NOM + " like '%" + inputText + "%'", null,  null, null, null, null);
		  }
		  
		  if (mCursor != null) 
		  {
			  mCursor.moveToFirst();
		  }
		  return mCursor;

}


 public Cursor fetchAllContacts() 
 {
	    
	    //String countQuery = "SELECT  * FROM " + SQLITE_TABLE;
        //Cursor cursor = mDb.rawQuery(countQuery, null);
        //cursor.close();
	    
		//Integer result = cursor.getCount();
	 	//cursor = mDb.query(SQLITE_TABLE, columns, null, null, null, null, null, null  );
	 	
	 	Cursor cursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, KEY_NOM, KEY_PRENOM, KEY_ADRESSE, KEY_EMAIL, KEY_PORTABLE, KEY_FIXE , KEY_PHOTOGRAPH}, null, null, null, null, null);
	 
	 	//Cursor cursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, null, null, null, null, null);

	 	if (cursor != null)
	 	{
	 		cursor.moveToFirst();
	 	}
	 	return cursor;
 }

 /*
 public void insertSomeCountries() 
 {
		createCountry("AFG","Afghanistan","Asia","Southern and Central Asia");
		createCountry("ALB","Albania","Europe","Southern Europe");
		createCountry("DZA","Algeria","Africa","Northern Africa");
		createCountry("ASM","American Samoa","Oceania","Polynesia");
		createCountry("AND","Andorra","Europe","Southern Europe");
		createCountry("AGO","Angola","Africa","Central Africa");
		createCountry("AIA","Anguilla","North America","Caribbean");
 }
 */
 
public boolean Check_contact_doublon(String champ1, String val1, String champ2, String val2 ) 
{

		String query = "Select * FROM " + SQLITE_TABLE + " WHERE " + champ1 + " =  \"" + val1 + "\"" + " AND " + champ2 + " =  \"" + val2  + "\"";
		Cursor cursor = mDb.rawQuery(query, null);
		Integer result = cursor.getCount();
	
		if(cursor.getCount() <= 0)
		{
			cursor.close();
			return false;
		}

		cursor.close();
		return true;
	
}	 
 
 public boolean CheckIsDataAlreadyInDB(String TableName, String dbfield, String fieldValue) 
 {
	 
	 				String champ1 = "code";
	 				String valeur1 = "ALB";
	 				String champ2 = "continent";
	 				String valeur2 = "Europelll";
	 				String query = "Select * FROM " + SQLITE_TABLE + " WHERE " + champ1 + " =  \"" + valeur1 + "\"" + " AND " + champ2 + " =  \"" + valeur2  + "\"";
	 					
	
	 				Cursor cursorffff = mDb.rawQuery(query, null);
	 				Integer result = cursorffff.getCount();
	 				
	 				champ1 = "code";
	 				valeur1 = "ALB";
	 				query = "Select * FROM " + SQLITE_TABLE + " WHERE " + champ1 + " =  \"" + valeur1 + "\"";
	  				cursorffff = mDb.rawQuery(query, null);
	 				result = cursorffff.getCount();
	 				
	 				
	 
	 				String countQuery = "SELECT  * FROM " + SQLITE_TABLE;
	 				Cursor cursor = mDb.rawQuery(countQuery, null);
	 
				    String Query = "Select * from " + SQLITE_TABLE; // + " where " + dbfield + " = " + fieldValue;
				    cursor = mDb.rawQuery(Query, null);
			        if(cursor.getCount() <= 0)
			        {
			            cursor.close();
			            return false;
			        }

			        cursor.close();
				    return true;
} 
 
 
//Add Contact
public boolean addContact(Contact contact)
{
	
					ContentValues vals = new ContentValues();
					vals.put(KEY_NOM, contact.getNom());
					vals.put(KEY_PRENOM, contact.getPrenom());
					vals.put(KEY_ADRESSE, contact.getAdresse());
					vals.put(KEY_EMAIL, contact.getEmail());
					vals.put(KEY_PORTABLE, contact.getPortable());
					vals.put(KEY_FIXE, contact.getFixe());
					vals.put(KEY_PHOTOGRAPH, contact.getPhotograph());
					
					long i = mDb.insert(SQLITE_TABLE, null, vals);
					mDb.close();
					
					 if(i != 0)
					 {
				       	return true;
				     }
					 else
					 {
				       	return false;
				     }
}
 
//Update contact contact
public boolean updateContact(Contact contact)
{
/*				    
					 String COLUMN_ID = "id";
					 String COLUMN_NOM = "nom";
					 String COLUMN_PRENOM = "prenom";
					 String COLUMN_ADRESSE = "adresse";
					 String COLUMN_EMAIL = "email";
					 String COLUMN_PORTABLE = "portable";
					 String COLUMN_FIXE = "fixe";
					 String COLUMN_PHOTOGRAPH = "photograph";
		
					 ContentValues vals = new ContentValues();
					 vals.put(COLUMN_NOM, contact.getNom());
					 vals.put(COLUMN_PRENOM, contact.getPrenom());
					 vals.put(COLUMN_ADRESSE, contact.getAdresse());
					 vals.put(COLUMN_EMAIL, contact.getEmail());
					 vals.put(COLUMN_PORTABLE, contact.getPortable());
					 vals.put(COLUMN_FIXE, contact.getFixe());
					 vals.put(COLUMN_PHOTOGRAPH, contact.getPhotograph());
*/		
		 
//					 String COLUMN_ID = "_id";
//					 String COLUMN_A = "code";
//					 String COLUMN_B = "name";
//					 String COLUMN_C = "continent";
//					 String COLUMN_D = "region";
					 
//					 ContentValues vals = new ContentValues();
//					 int position = contact.getID();
//					 vals.put(COLUMN_A, contact.getNom());
//					 vals.put(COLUMN_B, contact.getPrenom());
//					 vals.put(COLUMN_C, contact.getAdresse());
//					 vals.put(COLUMN_D, contact.getEmail());
					 
					 
					 ContentValues vals = new ContentValues();
					 vals.put(KEY_NOM, contact.getNom());
					 vals.put(KEY_PRENOM, contact.getPrenom());
					 vals.put(KEY_ADRESSE, contact.getAdresse());
					 vals.put(KEY_EMAIL, contact.getEmail());
					 vals.put(KEY_PORTABLE, contact.getPortable());
					 vals.put(KEY_FIXE, contact.getFixe());
					 vals.put(KEY_PHOTOGRAPH, contact.getPhotograph());
					 
					 
				    // updating row
					//  String countQuery = "SELECT  * FROM " + SQLITE_TABLE;
				    //  Cursor cursor = mDb.rawQuery(countQuery, null);
				    //   cursor.close();
					 
					// 	Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, null, null, null, null, null);
					 
				    int i = mDb.update(SQLITE_TABLE, vals, KEY_ROWID + " = ?",  new String[] { String.valueOf(contact.getID()) });
				     
					mDb.close();
				     
				    if(i != 0)
				    {
				     	return true;
				    }
				    else
				    {
				     	return false;
				    }
					
}

	
		public boolean deleteContact(int id)
		{
				 			String COLUMN_ID = "_id";
				 			id = id + 1;
				 			
							int i = mDb.delete(SQLITE_TABLE, COLUMN_ID + " = ?",  new String[] { String.valueOf(id) });
					     
							//db.close();
					     
							if(i != 0)
							{
								return true;
							}
							else
							{
								return false;
							}
		}


}