package com.yuji.ec.utility;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.evernote.edam.notestore.NoteList;
import com.yuji.ec.common.CommonUtil;
import com.yuji.ec.common.Constant;
import com.yuji.ec.db.DatabaseHelper;
import com.yuji.ec.db.Note;
import com.yuji.ec.db.NoteDao;
import com.yuji.ec.utility.EvernoteUtil.Error;

public class NoteUpdator {
	private static NoteUpdator instance = null;
	private static Object obj = new Object();

	public static NoteUpdator getInstance() {
		if (instance == null) {
			synchronized (obj) {
				if (instance == null) {
					instance = new NoteUpdator();
				}
			}
		}
		return instance;
	}

	private NoteUpdator() {

	}

	public void update(Context context, int noteItemType, String guid) {
		try {
			EvernoteUtil util = EvernoteUtil.getInstance();
			String username = PasswordUtil.getUsername(context);
			String password = PasswordUtil.getPassword(context);
			if (!CommonUtil.isNull(username) && !CommonUtil.isNull(password)) {
				util.setConfig(username, password);
			} else {
				return;
			}

			List<NoteList> noteListList;
			switch (noteItemType) {
			case Constant.NOTE_ITEM_TYPE_NOTE_BOOK:
				noteListList = util.getNoteListByNotebook(guid);
				break;
			case Constant.NOTE_ITEM_TYPE_TAG:
				noteListList = util.getNoteListByTag(guid);
				break;
			default:
				noteListList = util.getNoteList();
				break;
			}

			if (util.getErrorCode() != Error.NONE) {
				return;
			}

			List<Note> list = util.getNoteContentList(noteListList);
			if (list == null) {
				// NOT_FOUND
				return;
			}

			DatabaseHelper helper = DatabaseHelper.getInstance();
			SQLiteDatabase db = helper.getWritableDatabase();
			NoteDao dao = (NoteDao) NoteDao.getInstance();

			synchronized (obj) {
				db.beginTransaction();
				try {
					dao.deleteNT();
					for (Note note : list) {
						dao.addNT(note);
					}
					db.setTransactionSuccessful();
				} finally {
					db.endTransaction();
				}
			}
		} catch (Exception e) {
			Debug.d(this, null, e);
		}
	}
}
