package com.xlg.forkids.db.helpers;

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

import com.xlg.forkids.baseitems.BaseContactsContact;
import com.xlg.forkids.baseitems.PinyinParser;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

/** ÁªÏµÈËÏà¹ØµÄÊý¾Ý¿â°ïÖúÀà */
public class ContactsDbHelper extends BaseDbHelper {
	public static final String tableName = "contacts";
	private static ContactsDbHelper mInstance = null;

	public static final String Id = "id";
	private static final String UserCode = "userCode";
	public static final String Status = "status";
	private static final String Name = "name";
	private static final String NamePinYin = "namePinYin";
	private static final String Phone = "phone";
	private static final String HeadImage = "headImage";
	private static final String LastChat = "lastChat";

	/** »ñÈ¡È«¾Öµ¥Àý */
	public static ContactsDbHelper getInstance(Context context) {
		if (null == mInstance) {
			mInstance = new ContactsDbHelper(context);
		}
		mInstance.createTableIfNotExist();
		return mInstance;
	}

	ContactsDbHelper(Context context) {
		super(context);
		// if (null != mDatabaseName)
		// createTableIfNotExist();
	}

	/** ¹Ø±ÕÊý¾Ý¿âÁ¬½Ó£¬¹Ø±Õ±¾ÊµÀý */
	public void close() {
		// super.close();
		if (null != mInstance)
			mInstance = null;
	}

	/** Êý¾Ý±í²»´æÔÚÔò´´½¨Êý¾Ý±í */
	private void createTableIfNotExist() {
		if (!getDbHelper().isTableExist(tableName)) {
			// idÊÇ×Ô¶¯Ôö³¤µÄÖ÷¼ü£¬usernameºÍ passwordÎª×Ö¶ÎÃû£¬ textÎª×Ö¶ÎµÄÀàÐÍ
			String sql = "CREATE TABLE " + tableName
					+ " (_id integer primary key autoincrement, " + Id
					+ " integer, " + Status + " integer, " + LastChat
					+ " bigint, " + Name + " text, " + NamePinYin + " text, "
					+ Phone + " text, " + UserCode + " text, " + HeadImage
					+ " text)";
			getDbHelper().execSQL(sql);
		}
	}

	/** ½«ÁÐ±íÖÐµÄÓÃ»§¼ÓÈëµ½±¾µØdbÖÐ */
	public void insert(List<BaseContactsContact> list) {
		for (BaseContactsContact item : list) {
			if (null == item)
				continue;
			insert(item);
		}
	}

	/** ½«Ò»¸öÓÃ»§µÄÐÅÏ¢¼ÓÈëµ½±¾µØdbÖÐ.Èç¹ûÓÐÏàÍ¬µÄId/UserCode/name´æÔÚÔò¸üÐÂ */
	public void insert(BaseContactsContact item) {
		if (null == item)
			return;
		if (item.getId() <= 0)
			return;
		
		// createTableIfNotExist();
		// ²éÕÒÏàÍ¬IdµÄ
		boolean isExists = isUserExist(item.getId());
		String selection = isExists ? (Id + " = " + item.getId()) : "";
		// ²éÕÒÏàÍ¬userCodeµÄ
		if (!isExists)
			isExists = isUserExist(item.getUserCode());
		selection = isExists ? (UserCode + " = '" + item.getUserCode() + "'")
				: selection;
		// ²éÕÒÏàÍ¬nameµÄ
		if (!isExists)
			isExists = isUserExist(item.getName());
		selection = isExists ? (Name + " = '" + item.getName() + "'")
				: selection;

		ContentValues values = new ContentValues();
		values.put(Id, item.getId());
		values.put(UserCode, item.getUserCode());
		values.put(Status, item.getStatus());
		values.put(Name, item.getName());
		values.put(Phone, item.getPhone());
		values.put(HeadImage, item.getHeadImage());
		values.put(LastChat, item.getLastChat());
		values.put(NamePinYin,
				PinyinParser.getInstance().getSelling(item.getName()));

		if (!isExists) {
			getDbHelper().insert(tableName, values);
		} else {
			getDbHelper().update(tableName, values, selection, null);
		}
	}

	/** Í¨¹ýID²éÕÒÏàÍ¬µÄ¼ÇÂ¼ */
	public boolean isUserExist(int uId) {
		boolean ret = false;
		if (uId == -1)
			return ret;

		Cursor cursor = getDbHelper().findList(tableName, new String[] { Id },
				Id + " = " + uId, null, null, null, null);
		ret = cursor.getCount() > 0;
		cursor.close();
		return ret;
	}

	/** Í¨¹ý UserCode »ò name ²éÕÒÏàÍ¬µÄ¼ÇÂ¼ */
	public boolean isUserExist(String userCodeOrName) {
		boolean ret = false;
		if (userCodeOrName.equals(""))
			return ret;
		Cursor cursor = getDbHelper().findList(
				tableName,
				new String[] { Id },
				UserCode + " = '" + userCodeOrName + "' or " + Name + " = '"
						+ userCodeOrName + "'", null, null, null, null);
		ret = cursor.getCount() > 0;
		cursor.close();
		return ret;
	}

	/**
	 * Í¨¹ýÓÃ»§IDÉ¾³ýÒ»¸öÓÃ»§µÄÐÅÏ¢
	 * 
	 * @param id
	 *            ÓÃ»§µÄ ID
	 */
	public void delete(int id) {
		getDbHelper().delete(tableName, Id + " = " + id, null);
	}

	/**
	 * Í¨¹ýÓÃ»§µÇÂ¼ÃûÉ¾³ýÒ»¸öÓÃ»§ÐÅÏ¢
	 * 
	 * @param userCode
	 *            ÓÃ»§µÇÂ¼Ãû
	 */
	public void delete(String userCode) {
		getDbHelper().delete(tableName, UserCode + " = '" + userCode + "'",
				null);
	}

	private BaseContactsContact getContact(Cursor cursor) {
		BaseContactsContact item = new BaseContactsContact();
		item.setHeadImage(cursor.getString(cursor
				.getColumnIndexOrThrow(HeadImage)));
		item.setId(cursor.getInt(cursor.getColumnIndexOrThrow(Id)));
		item.setName(cursor.getString(cursor.getColumnIndexOrThrow(Name)));
		item.setPhone(cursor.getString(cursor.getColumnIndexOrThrow(Phone)));
		item.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow(Status)));
		item.setUserCode(cursor.getString(cursor
				.getColumnIndexOrThrow(UserCode)));
		item.setLastChat(cursor.getLong(cursor.getColumnIndexOrThrow(LastChat)));
		return item;
	}

	/** »ñÈ¡DbÖÐµÄÓÃ»§ÁÐ±í */
	public List<BaseContactsContact> getContacts(String name, int offset,
			int limit) {
		List<BaseContactsContact> tmp = new ArrayList<BaseContactsContact>();
		String sql = "select * from "
				+ tableName
				+ (isEmpty(name) ? "" : " where " + Name + " like '%" + name
						+ "%' ") + " order by " + NamePinYin;
		if (offset >= 0 && limit >= 0)
			sql += " limit " + limit + " offset " + offset;
		Cursor cursor = getDbHelper().rawQuery(sql);
		try {
			while (cursor.moveToNext()) {
				tmp.add(getContact(cursor));
			}
		} finally {
			cursor.close();
		}
		return tmp;
	}

	/** ·ÖÒ³»ñÈ¡ÎÒµÄ */
	// public List<BaseContactsContact> getMyFriends1(int offset, int limit) {
	// List<BaseContactsContact> tmp = new ArrayList<BaseContactsContact>();
	// String sql = "select * from " + tableName + " where status = "
	// + ContactsStatus.ADDED + " order by name";
	// if (offset >= 0 && limit >= 0)
	// sql += " limit " + limit + " offset " + offset;
	// Cursor cursor = getDbHelper().rawQuery(sql);
	// try {
	// while (cursor.moveToNext()) {
	// tmp.add(getContact(cursor));
	// }
	// } finally {
	// cursor.close();
	// }
	// return tmp;
	// }

	/** Í¨¹ýÓÃ»§Id²éÕÒÓÃ»§ */
	public BaseContactsContact getContact(int id) {
		BaseContactsContact bcc = null;
		Cursor cursor = getDbHelper().findList(tableName, null,
				Id + " = " + id, null, null, null, null);
		try {
			if (cursor.getCount() > 0) {
				cursor.moveToFirst();
				bcc = getContact(cursor);
			}
		} finally {
			cursor.close();
		}
		return bcc;
	}

	/** Í¨¹ýÓÃ»§code²éÕÒÓÃ»§ */
	public BaseContactsContact getContact(String userCode) {
		BaseContactsContact bcc = null;
		Cursor cursor = getDbHelper().findList(tableName, null,
				UserCode + " = '" + userCode + "'", null, null, null, null);
		try {
			if (cursor.getCount() > 0) {
				cursor.moveToFirst();
				bcc = getContact(cursor);
			}
		} finally {
			cursor.close();
		}
		return bcc;
	}
}
