#!/usr/bin/env python3

import re
import sqlite3

from pyarxi.io import expand_pj
from pyarxi.sql import Kan_t


def read_jr(nm):
    with open(expand_pj(nm), encoding='cp1251') as f:
        next(f)              # Skip date
        num = int(next(f))   # Line count (check corrupted file)
        for line in f:
            line = line.strip()
            if line == '.':  # End of file
                break
            num -= 1
            yield line
        if num != 0 or line != '.':  # Checksum
            raise IOError("Corrupted file '" + nm + "'")


def _parse_table(nm, rgx, gen):
    r = re.compile(rgx)
    for i, line in enumerate(read_jr(nm)):
        m = r.match(line.strip())
        if not m:
            print("Error: in {:s}[{:d}]: {:s}".format(nm, i, line))
            continue
        yield gen(i, m)


def construct_kan(i, g):
    # onyomi должно выглядеть как '*aaa*bbb*ccc*ddd*' для удобства поиска ('/' ?)
    # g[3] ALT: '*{}*'.format('*'.join(g[3].split('/')))
    # e[0] ALT: '*{}*'.format(e[0].strip('*'))
    e = g[5].split('`')
    while len(e) < 6:
        e.append('')
    # Судя по всему, в базе ограничена длина поля kunyomi, поэтому в редких
    # случаях не влезающая часть его хранится в поле compounds.
    # Переносится в начало кунъёми
    # if $compounds =~ s/^_([^_]*)_//
    #     $kunyomi = $1.$kunyomi;
    # Если повторяется, то переносится в конец кунъёми.
    # if $compounds =~ s/^_([^_]*)_//
    #     $kunyomi .= $1;
    return Kan_t(i, int(g[0]), int(g[1]), int(g[2]), g[3], g[4], *e)


def parse_kan(nm):
    return _parse_table(nm, r'^(\d\d)(\d\d)(\d{5})([\d\/]*)([^`]*)`(.*)$',
                        lambda i, m: construct_kan(i, m.groups()))


def gen_db(path=expand_pj('@/raw/yarxi.db')):
    with sqlite3.connect(path) as conn:
        # if not fs.exists(path) or os.stat(path).st_size == 0:
        with open(expand_pj(':/db-schema.sql'), 'rt') as f:
            # TRY:FIND: use external arguments/variables when executing db-schema.sql
            conn.executescript(f.read())

        tbl = 'Kanji'
        # for obj in parse_kan('@/jr_kan.txt'):
        #     print(obj)

        SQL_kan = "insert into {} ({}) values ({})".format(
            tbl, ', '.join(Kan_t._fields),
            ', '.join([':' + s for s in Kan_t._fields]))
        cursor = conn.cursor()
        cursor.executemany(SQL_kan, parse_kan('@/raw/jr_kan.txt'))

if __name__ == '__main__':
    gen_db()
