~vono22/narau/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
 *  Copyright (C) 2012 Yvon TANGUY
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.vono.narau.db;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

import org.vono.narau.R;
import org.vono.narau.common.Common;
import org.vono.narau.models.dictionary.Entry;
import org.vono.narau.models.dictionary.KanjiElement;
import org.vono.narau.models.dictionary.ReadingElement;
import org.vono.narau.models.dictionary.Sense;
import org.vono.narau.preferences.Preferences;
import org.vono.narau.utils.Language;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.util.SparseArray;

/**
 * Function to manage the dictionaries.
 * 
 */
public class DictionaryDB extends CommonDB {
	private static final String TAG = DictionaryDB.class.getSimpleName();

	static final int VALUE_DB_VERSION = 2;

	private static final String TABLE_KANJI_ELEM = "k_ele";
	private static final String TABLE_READING_ELEM = "r_ele";
	private static final String TABLE_SENSE = "sense";
	private static final String TABLE_GLOSS = "gloss";

	private static final String COL_ID = "id";
	private static final String COL_KEB = "keb";
	private static final String COL_REB = "reb";
	private static final String COL_PRI = "pri";
	private static final String COL_INF = "inf";
	private static final String COL_NUM = "num";
	private static final String COL_STAGK = "stagk";
	private static final String COL_STAGR = "stagr";
	private static final String COL_POS = "pos";
	private static final String COL_XREF = "xref";
	private static final String COL_GLOSS_TEXT = "gloss";

	private static final String[] ARRAY_COL_ID = { COL_ID };

	/**
	 * COL_KEB, COL_PRI, COL_INF
	 */
	private static final String[] ARRAY_COLS_KELE = { COL_KEB, COL_PRI, COL_INF };

	/**
	 * COL_REB, COL_PRI, COL_INF
	 */
	private static final String[] ARRAY_COLS_RELE = { COL_REB, COL_PRI, COL_INF };

	/**
	 * COL_STAGK, COL_STAGR, COL_POS, COL_XREF
	 */
	private static final String[] ARRAY_COLS_SENSE = { COL_STAGK, COL_STAGR, COL_POS, COL_XREF, COL_NUM };

	/**
	 * COL_GLOSS_TEXT
	 */
	private static final String[] ARRAY_COLS_GLOSS = { COL_GLOSS_TEXT };

	/**
	 * A big where clause, to match only word (which can have a space or a
	 * slash, before and after.
	 */
	private static final String WHERE_LIKE_WORDMATCH_SELECTION = "%1$s LIKE ? " + "OR %1$s LIKE ? " + "OR %1$s LIKE ? "
			+ "OR %1$s LIKE ? " + "OR %1$s LIKE ? " + "OR %1$s LIKE ? " + "OR %1$s LIKE ? " + "OR %1$s LIKE ? "
			+ "OR %1$s LIKE ?";
	private static final String[] WHERE_LIKE_WORDMATCH_SELECTION_ARGS = { "%1$s", "%1$s %%", "%1$s/%%", "%% %1$s",
			"%%/%1$s", "%% %1$s %%", "%%/%1$s/%%", "%%/%1$s %%", "%% %1$s/%%" };
	private static final String WHERE_LIKE = "%1$s LIKE ?";
	private static final String WHERE_ID_EQUAL = COL_ID + " = ?";
	private static final String WHERE_ID_NUM_EQUAL = WHERE_ID_EQUAL + " AND " + COL_NUM + " = ?";

	// Database management:
	private static InfosDB mainDB = null;
	private static final ArrayList<InfosDB> langsDB = new ArrayList<InfosDB>();
	private static DatabaseState state;
	private static SparseArray<Entry> loadedEntries = null;

	/**
	 * Init the DictionaryDB.state value
	 */
	static void initDB() {
		DictionaryDB.state = DatabaseState.bad;

		boolean haveMain = false;
		boolean haveLang = false;
		final ArrayList<InfosDB> listDBs = CommonDB.listDBInfos;
		final int size = listDBs.size();
		for (int i = 0; i < size; i++) {
			final InfosDB db = listDBs.get(i);
			if (db.type == DatabaseType.dictonary) {
				if (Language.JAPANESE.equals(db.language)) {
					haveMain = true;
					DictionaryDB.mainDB = db;
				} else {
					haveLang = true;
					DictionaryDB.langsDB.add(db);
				}
			}
		}
		if (haveMain && haveLang) {
			DictionaryDB.state = DatabaseState.good;
		}

		DictionaryDB.loadedEntries = new SparseArray<Entry>();
	}

	protected static void cleanDB() {
		DictionaryDB.state = DatabaseState.bad;
		DictionaryDB.langsDB.clear();
		DictionaryDB.mainDB = null;
		if (null != loadedEntries) {
			DictionaryDB.loadedEntries.clear();
			DictionaryDB.loadedEntries = null;
		}
	}

	static boolean isReady() {
		return DictionaryDB.state == DatabaseState.good;
	}

	/**
	 * Can be called only by Preferences.getLangsPriorities()<br/>
	 * Use Preferences.getLangsPriorities() instead
	 * 
	 * @return All available translation languages in the dictionary database.
	 */
	public static ArrayList<Language> getLangs() {

		ArrayList<Language> languages = null;
		if (DatabaseState.good == DictionaryDB.state) {
			languages = new ArrayList<Language>(langsDB.size());
			for (InfosDB infosDB : langsDB) {
				languages.add(infosDB.language );
			}
		}
		Collections.sort(languages);

		return languages;
	}

	private static ArrayList<InfosDB> getSortedListLangDB() {
		final ArrayList<InfosDB> listLangDB = new ArrayList<InfosDB>();
		final ArrayList<Language> languages = Preferences.getLangsPriorities(DatabaseType.dictonary);

		// Quick & Dirty
		for (Language language : languages) {
			for (InfosDB dbInfos : DictionaryDB.langsDB) {
				if (language.equals(dbInfos.language)) {
					listLangDB.add(dbInfos);
				}
			}
		}

		return listLangDB;
	}

	public static Entry loadEntry(int id) {
		Entry entry = loadedEntries.get(id);
		if (null == entry) {
			final String[] selectionArgs = new String[1];
			selectionArgs[0] = Integer.toString(id);

			// get kanji element(s)
			ArrayList<KanjiElement> k_ele = DictionaryDB.loadKanjiElements(selectionArgs);

			// get reading element(s)
			ArrayList<ReadingElement> r_ele = DictionaryDB.loadReadingElements(selectionArgs);

			// get sense element(s)
			ArrayList<Sense> senses = DictionaryDB.loadSenseElements(selectionArgs);

			// Build entry:
			entry = new Entry(id);
			entry.k_ele = k_ele;
			entry.r_ele = r_ele;
			entry.senses = senses;

			loadedEntries.put(id, entry);
		}

		return entry;
	}

	private static ArrayList<KanjiElement> loadKanjiElements(String[] selectionArgs) {
		ArrayList<KanjiElement> k_ele = null;
		Cursor cursor = mainDB.db.query(TABLE_KANJI_ELEM, ARRAY_COLS_KELE, WHERE_ID_EQUAL, selectionArgs, null, null,
				COL_NUM);
		if (cursor.moveToFirst()) {
			k_ele = new ArrayList<KanjiElement>(cursor.getCount());
			do {
				KanjiElement ke = new KanjiElement();
				ke.keb = cursor.getString(0);

				String tmp = cursor.getString(1);
				if (null != tmp) {
					ke.ke_pri = Common.splitString(tmp, Common.SLASH);
				}

				tmp = cursor.getString(2);
				if (null != tmp) {
					ke.ke_inf = Common.splitString(tmp, Common.SLASH);
				}

				k_ele.add(ke);

			} while (cursor.moveToNext());
		}
		cursor.close();

		return k_ele;
	}

	private static ArrayList<ReadingElement> loadReadingElements(String[] selectionArgs) {
		ArrayList<ReadingElement> r_ele = null;
		Cursor cursor = mainDB.db.query(TABLE_READING_ELEM, ARRAY_COLS_RELE, WHERE_ID_EQUAL, selectionArgs, null, null,
				COL_NUM);
		if (cursor.moveToFirst()) {
			r_ele = new ArrayList<ReadingElement>(cursor.getCount());

			do {
				ReadingElement re = new ReadingElement();
				re.reb = cursor.getString(0);

				String tmp = cursor.getString(1);
				if (null != tmp) {
					re.re_pri = Common.splitString(tmp, Common.SLASH);
				}

				tmp = cursor.getString(2);
				if (null != tmp) {
					re.re_inf = Common.splitString(tmp, Common.SLASH);
				}
				r_ele.add(re);

			} while (cursor.moveToNext());

		} else {
			Log.e(TAG, "no reading element for: " + selectionArgs[0]);
		}
		cursor.close();

		return r_ele;
	}

	private static ArrayList<Sense> loadSenseElements(String[] selectionArgs) {
		ArrayList<Sense> senses = null;
		Cursor cursor = mainDB.db.query(TABLE_SENSE, ARRAY_COLS_SENSE, WHERE_ID_EQUAL, selectionArgs, null, null,
				COL_NUM);
		if (cursor.moveToFirst()) {
			senses = new ArrayList<Sense>(cursor.getCount());

			final ArrayList<InfosDB> lLangsDB = DictionaryDB.langsDB;
			final int numLangs = lLangsDB.size();

			final String[] glossSelectionArgs = new String[2];
			glossSelectionArgs[0] = selectionArgs[0];

			do {
				Sense sense = new Sense();
				sense.stagk = cursor.getString(0);
				sense.stagr = cursor.getString(1);
				sense.pos = cursor.getString(2);
				sense.xref = cursor.getString(3);
				int num = cursor.getInt(4);

				sense.glosses = new HashMap<Language, String>(numLangs);
				glossSelectionArgs[1] = Integer.toString(num);
				for (int i = 0; i < numLangs; i++) {
					final InfosDB infosDB = lLangsDB.get(i);
					String gloss = loadGloss(infosDB, glossSelectionArgs);
					if (null != gloss) {
						sense.glosses.put(infosDB.language, gloss);
					}
				}

				senses.add(sense);
			} while (cursor.moveToNext());
		}
		cursor.close();

		return senses;
	}

	private static String loadGloss(InfosDB infosDB, String[] selectionArgs) {
		String gloss = null;

		Cursor cursor = infosDB.db.query(TABLE_GLOSS, ARRAY_COLS_GLOSS, WHERE_ID_NUM_EQUAL, selectionArgs, null, null,
				null);
		if (cursor.moveToFirst()) {
			gloss = cursor.getString(0);
		}
		cursor.close();

		return gloss;
	}

	/**
	 * Common class for Dictionary iterators.
	 * 
	 */
	private static abstract class InternalIterator implements Iterator<Entry> {
		protected Cursor cursor;
		protected ArrayList<InfosDB> dbLangs;
		protected String limit;

		public InternalIterator() {
			this.cursor = null;
			this.dbLangs = DictionaryDB.getSortedListLangDB();
			this.limit = null;
		}

		@Override
		protected void finalize() throws Throwable {
			this.close();
			super.finalize();
		}

		/**
		 * Close the SQLite connection.
		 */
		public void close() {
			if (null != this.cursor) {
				this.cursor.close();
				this.cursor = null;
			}
		}

		public boolean hasNext() {
			boolean ret = false;
			if (null != this.cursor && !this.cursor.isLast()) {
				ret = true;
			}
			return ret;
		}

		/**
		 * 
		 * @return the number of elements fetch, or -1 if close.
		 */
		public int getCount() {
			if (null != this.cursor && !this.cursor.isClosed()) {
				return this.cursor.getCount();
			}
			return -1;
		}

		/**
		 * throw UnsupportedOperationException()
		 */
		public void remove() {
			throw new UnsupportedOperationException("Can't delete data from the dictionary database");
		}

	}

	/**
	 * The dictionary iterator used by the dictionary activity.
	 */
	public static class DictionaryIterator extends InternalIterator {
		private boolean wordMatch;

		public DictionaryIterator() {
			super();
			super.limit = Integer.toString(Preferences.getInt(R.string.prefNameDictionaryMaxResult));
			this.wordMatch = Preferences.getBoolean(R.string.prefNameDictionaryWordMatch);
		}

		public boolean searchFromJpnKana(String text, boolean withLimit) {
			super.close();

			String selection = String.format(WHERE_LIKE, COL_REB);
			String[] selectionArgs = new String[1];
			if (this.wordMatch) {
				selectionArgs[0] = text;
			} else {
				selectionArgs[0] = "%" + text + "%";
			}

			String limitClause = withLimit ? super.limit : null;

			super.cursor = DictionaryDB.mainDB.db.query(TABLE_READING_ELEM, ARRAY_COL_ID, selection, selectionArgs,
					null, null, null, limitClause);

			return super.cursor.getCount() > 0;
		}

		public boolean searchFromJpnKanji(String text, boolean withLimit) {
			super.close();

			String selection = String.format(WHERE_LIKE, COL_KEB);
			String[] selectionArgs = new String[1];
			if (this.wordMatch) {
				selectionArgs[0] = text;
			} else {
				selectionArgs[0] = "%" + text + "%";
			}

			String limitClause = withLimit ? super.limit : null;

			super.cursor = DictionaryDB.mainDB.db.query(TABLE_KANJI_ELEM, ARRAY_COL_ID, selection, selectionArgs, null,
					null, null, limitClause);

			return super.cursor.getCount() > 0;
		}

		public boolean searchToJpn(String text, Language language, boolean withLimit) {
			super.close();

			SQLiteDatabase db = null;
			for (InfosDB infosDB : DictionaryDB.langsDB) {
				if (infosDB.language.equals(language)) {
					db = infosDB.db;
					break;
				}
			}

			if (null == db) {
				return false;
			}

			final String selection;
			final String[] selectionArgs;
			if (this.wordMatch) {
				selection = String.format(WHERE_LIKE_WORDMATCH_SELECTION, COL_GLOSS_TEXT);
				final int lenWhere = WHERE_LIKE_WORDMATCH_SELECTION_ARGS.length;
				selectionArgs = new String[lenWhere];
				for (int i = 0; i < lenWhere; i++) {
					selectionArgs[i] = String.format(WHERE_LIKE_WORDMATCH_SELECTION_ARGS[i], text);
				}
			} else {
				selection = String.format(WHERE_LIKE, COL_GLOSS_TEXT);
				selectionArgs = new String[1];
				selectionArgs[0] = "%" + text + "%";
			}

			String limitClause = withLimit ? super.limit : null;

			super.cursor = db.query(TABLE_GLOSS, ARRAY_COL_ID, selection, selectionArgs, null, null, null, limitClause);

			return super.cursor.getCount() > 0;
		}

		public Entry next() {
			Entry entry = null;

			if (null != super.cursor && !super.cursor.isClosed() && cursor.moveToNext()) {
				int id = cursor.getInt(0);
				entry = DictionaryDB.loadEntry(id);
			}
			return entry;
		}

	}

	/**
	 * An iterator for the KanjiToWords activity.
	 * 
	 */
	public static class KanjiToWordsIterator extends InternalIterator {

		private static final String[] ARRAY_COLS_KANJI = { "id", "keb", "pri" };
		private static final String[] ARRAY_COLS_READING = { "reb" };
		private static final String SELECTION_KANJI = "keb like ? and num=?";
		private static final String SELECTION_READING = "id=?";
		private static final String SELECTION_GLOSS = "id=? and num=?";
		private static final String ORDER_READING = "num asc";
		private static final String ORDER_GLOSS = "num asc";

		public KanjiToWordsIterator() {
			super();
			super.limit = Integer.toString(Preferences.getInt(R.string.prefNameKanjiToWordsNWTL));
		}

		/**
		 * 
		 * @param codepoint
		 *            Set the current kanji to look words
		 * @param noLimit
		 *            If true, remove the limit of results in the query
		 * @return true if there is some words founds
		 */
		public boolean setCodepoint(int codepoint, boolean noLimit) {

			if (this.cursor != null) {
				this.cursor.close();
			}
			final String[] selectionArgs = new String[2];
			selectionArgs[0] = "%" + new String(Character.toChars(codepoint)) + "%";
			selectionArgs[1] = "0";
			String limitClause = this.limit;
			if (noLimit) {
				limitClause = null;
			}
			this.cursor = DictionaryDB.mainDB.db.query(DictionaryDB.TABLE_KANJI_ELEM,
					KanjiToWordsIterator.ARRAY_COLS_KANJI, KanjiToWordsIterator.SELECTION_KANJI, selectionArgs, null,
					null, null, limitClause);
			return this.cursor.getCount() != 0;
		}

		/**
		 * @return A minimal Dictionary Entry (id/keb/pri, common reading, one
		 *         sense).
		 */
		public Entry next() {
			if (null != this.cursor && this.cursor.moveToNext()) {

				final int id = cursor.getInt(0);
				final String keb = cursor.getString(1);
				final String pri = cursor.getString(2);

				// The kanji element
				Entry entry = new Entry(id);
				entry.partial = true;
				KanjiElement ke = new KanjiElement();
				ke.keb = keb;

				ke.ke_pri = Common.splitString(pri, Common.SLASH);
				entry.k_ele = new ArrayList<KanjiElement>(1);
				entry.k_ele.add(ke);

				// The reading element
				String[] selectionArgs = new String[1];
				selectionArgs[0] = Integer.toString(id); // id=

				Cursor lcursor = DictionaryDB.mainDB.db.query(TABLE_READING_ELEM,
						KanjiToWordsIterator.ARRAY_COLS_READING, KanjiToWordsIterator.SELECTION_READING, selectionArgs,
						null, null, KanjiToWordsIterator.ORDER_READING);
				if (lcursor.moveToFirst()) {
					entry.r_ele = new ArrayList<ReadingElement>(lcursor.getCount());
					do {
						ReadingElement re = new ReadingElement();
						re.reb = lcursor.getString(0);
						entry.r_ele.add(re);
					} while (lcursor.moveToNext());
				}
				lcursor.close();
				// Sense
				selectionArgs = new String[2];
				selectionArgs[0] = Integer.toString(id); // id=
				selectionArgs[1] = Integer.toString(0); // num=

				final ArrayList<InfosDB> lDBLangs = this.dbLangs;
				final int langCount = lDBLangs.size();
				entry.senses = new ArrayList<Sense>();
				for (int i = 0; i < langCount; i++) {
					final InfosDB infosDB = lDBLangs.get(i);
					lcursor = infosDB.db.query(DictionaryDB.TABLE_GLOSS, DictionaryDB.ARRAY_COLS_GLOSS,
							KanjiToWordsIterator.SELECTION_GLOSS, selectionArgs, null, null,
							KanjiToWordsIterator.ORDER_GLOSS);
					if (lcursor.moveToFirst()) {
						Sense sense = new Sense();
						sense.glosses = new HashMap<Language, String>(1);
						sense.glosses.put(infosDB.language, lcursor.getString(0));
						entry.senses.add(sense);
						i = langCount;
					}
					lcursor.close();
				}
				return entry;
			}
			this.cursor.close();
			this.cursor = null;
			return null;
		}

	}

}