#!/usr/bin/python3

import glob
import os
import yaml
import sys

def append_entry(entries, doc):
    entry = None
    if 'result' in doc and '맞춤법 검사' in doc['result']:
        if '제외' not in doc['result']['맞춤법 검사']:
            entry = doc['result']['맞춤법 검사']
    if entry is not None:
        keys = entry.keys()
        REPLACE = {'표제어':'word', '품사':'pos', '속성':'props'}
        e = {}
        for k in keys:
            if k in REPLACE:
                e[REPLACE[k]] = entry[k]
        if 'word' not in e or 'pos' not in e:
            print(entry)
            print(e)
            print(doc)
            abort()
        if e['pos'] == '의존 명사':
            e['pos'] = '명사'
        elif e['pos'] == '보조 동사':
            e['pos'] = '동사'
        elif e['pos'] == '보조 형용사':
            e['pos'] = '형용사'
        entries.append(e)

def process_file(filename, entries):
    documents = yaml.load_all(open(filename), Loader=yaml.FullLoader)
    for k in documents:
        append_entry(entries, k)

def output_file(filename, entries):
    entries.sort(key=lambda x : x['word'])
    with open(filename, 'w') as outfile:
        outfile.write('# 자동으로 생성된 파일입니다. 직접 편집하지 마십시오.\n')
        outfile.write('# This file is auto generated. Do not edit this file.\n')
        outfile.write('# The file is licensed under the GPL version 3 or later.\n')
        yaml_entry = {'entries': entries}
        yaml.dump(yaml_entry, outfile, allow_unicode=True, default_flow_style=False, indent=2)
    print(filename)

def find_and_save(dir, filename):
    yaml_filenames = glob.glob(dir + '/*.yaml')
    entries = []
    print('Total %d files...' % len(yaml_filenames))
    count = 0
    for yaml_filename in yaml_filenames:
        process_file(yaml_filename, entries)
        count += 1
        sys.stdout.write('%d...' % count)
        sys.stdout.flush()
    sys.stdout.write('\n')
    output_file(filename, entries)

if __name__ == '__main__':
    dir = './entries'
    outfile = '../dict-ko-data.yaml'
    find_and_save(dir, outfile)
