package com.example.contactslist;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ContactsDAO {
	// Database fields
	private SQLiteDatabase database;
	private SQLiteContactHelper dbHelper;
	
	private String[] allColumns = { SQLiteContactHelper.COL_CONTACT_ID,
			SQLiteContactHelper.COL_CONTACT, SQLiteContactHelper.COL_CONTACT_NUM };

	public ContactsDAO(Context context) {
		dbHelper = new SQLiteContactHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public List<String[]> getAllContacts() {
		List<String[]> contacts = new ArrayList<String[]>();

		Cursor cursor = database.query(SQLiteContactHelper.CONTACT_TABLE,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			String[] contact = cursorToContact(cursor);
			contacts.add(contact);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return contacts;
	}

	public String[] createContactEntry(String name, String number) {
		
		ContentValues values = new ContentValues();
		
		values.put(SQLiteContactHelper.COL_CONTACT, name);
		values.put(SQLiteContactHelper.COL_CONTACT_NUM, number);

		long insertId = database.insert(SQLiteContactHelper.CONTACT_TABLE, null,
				values);
		Cursor cursor = database.query(SQLiteContactHelper.CONTACT_TABLE,
				allColumns, SQLiteContactHelper.COL_CONTACT_ID + " = " + insertId,
				null, null, null, null);

		cursor.moveToFirst();
		String[] newContact = cursorToContact(cursor);
		cursor.close();
		return newContact;
	}

	public void deleteItem(String contact) {
		database.delete(SQLiteContactHelper.CONTACT_TABLE,
				SQLiteContactHelper.COL_CONTACT + " = " + contact, null);
	}

	private String[] cursorToContact(Cursor cursor) {
		String[] contact = new String[2];

		contact[0] = cursor.getString(1);
		contact[1] = cursor.getString(2);
		return contact;
	}
}
