CREATE VIEW "JMdict_EntryByKana"("kana", "entryId")
AS
SELECT
  "JMdict_ReadingElement"."reading" AS "kana",
  "JMdict_ReadingElement"."entryId" AS "entryId"
FROM "JMdict_ReadingElement";


CREATE VIEW "JMdict_EntryByEnglish"("english", "entryId")
AS
SELECT
  "JMdict_SenseGlossary"."phrase" AS "english",
  "JMdict_Sense"."senseId" AS "entryId"
FROM "JMdict_SenseGlossary" JOIN "JMdict_Sense" USING("senseId");


CREATE VIEW "JMdict_BaseAndFurigana"("entryId", "base", "furigana", "isFirst", "kanjiOrderNum", "readingOrderNum")
AS
SELECT
  "JMdict_Entry"."entryId" AS "entryId",
  CASE WHEN (
    "JMdict_KanjiElement"."reading" IS NOT NULL
    AND NOT "JMdict_ReadingElement"."readingDoesNotMatchKanji"
  )
    THEN "JMdict_KanjiElement"."reading"
    ELSE "JMdict_ReadingElement"."reading"
  END AS "base",
  CASE WHEN (
    "JMdict_KanjiElement"."reading" IS NOT NULL
    AND NOT "JMdict_ReadingElement"."readingDoesNotMatchKanji"
  )
    THEN "JMdict_ReadingElement"."reading"
    ELSE NULL
  END AS "furigana",
  COALESCE("JMdict_KanjiElement"."orderNum", 1)
      + "JMdict_ReadingElement"."orderNum"
      = 2
  AS "isFirst",
  "JMdict_KanjiElement"."orderNum" AS "kanjiOrderNum",
  "JMdict_ReadingElement"."orderNum" AS "readingOrderNum"
FROM "JMdict_Entry"
LEFT JOIN "JMdict_KanjiElement" USING("entryId")
LEFT JOIN "JMdict_ReadingElement" USING("entryId");


CREATE VIEW "JMdict_EntryCommon"("entryId")
AS
SELECT DISTINCT "entryId"
FROM "JMdict_KanjiElementScore"
FULL OUTER JOIN "JMdict_ReadingElementScore" USING("entryId")
WHERE "JMdict_ReadingElementScore"."common" = 1
   OR "JMdict_KanjiElementScore"."common" = 1;


-- TODO: Make it possible to match words that contain the
--       kanji as an infix

CREATE VIEW "KANJIDIC_ExampleEntries"("kanji", "entryId")
AS
SELECT
  "JMdict_KanjiElement"."entryId",
  "KANJIDIC_Character"."literal" AS "kanji",
  "JMdict_KanjiElement"."reading"
FROM
  "KANJIDIC_Character"
JOIN "JMdict_KanjiElementFTS"
  ON "JMdict_KanjiElementFTS"."reading" MATCH "KANJIDIC_Character"."literal" || '*'
JOIN "JMdict_KanjiElement"
  ON "JMdict_KanjiElementFTS"."entryId" = "JMdict_KanjiElement"."entryId"
    AND "JMdict_KanjiElementFTS"."reading" LIKE '%' || "JMdict_KanjiElement"."reading"
JOIN "JMdict_KanjiElementScore"
  ON "JMdict_KanjiElement"."entryId" = "JMdict_KanjiElementScore"."entryId"
    AND "JMdict_KanjiElement"."reading" = "JMdict_KanjiElementScore"."reading"
WHERE "JMdict_KanjiElementScore"."common";


CREATE VIEW "RADKFILE_Radicals" AS
SELECT DISTINCT "radical" FROM "RADKFILE";
