# -*- coding: utf-8 -*-
import q41, q42

VERB = '動詞'
SAHEN = 'サ変接続'
PARTICLE = '助詞'
PARTICLE_WORD = 'を'

def check_include_sahen(d_pos1):
    if SAHEN in d_pos1:
        return True
    else:
        return False

def check_particle_word(d_sen):
    if PARTICLE_WORD in d_sen:
        return True
    else:
        return False

def check_include_verb(s_pos):
    if VERB in s_pos:
        return True
    else:
        return False

def make_sahen_pattern(combi_dict):
    sahen_dict = {}
    for k, v in sorted(combi_dict.items()):
        d_pos1 = v['dst_pos1'].split(',')
        if not check_include_sahen(d_pos1):
            continue
        d_sen = v['dst_sen'].split(' ')
        if not check_particle_word(d_sen):
            continue
        s_pos = v['src_pos'].split(',')
        if not check_include_verb(s_pos):
            continue
        s_idx = s_pos.index(VERB)
        s_base = v['src_base'].split(' ')
        s_verb_base = s_base[s_idx]
        s_sen = v['src_sen'].split(' ')
        s_verb = s_sen[s_idx]
        key = ''.join(d_sen) + s_verb_base
        if not key in sahen_dict:
            sahen_dict[key] = {}
            sahen_dict[key]['part'] = []
            sahen_dict[key]['sentence'] = []
            sahen_dict[key]['sentence_space'] = []
            sahen_dict[key]['d_sen'] = []
            sahen_dict[key]['s_verb'] = []
        sahen_dict[key]['d_sen'].append(' '.join(d_sen))
        sahen_dict[key]['s_verb'].append(s_verb)
    return sahen_dict

def get_verb_depend(sahen_dict, combi_dict):
    tmp_dict = sahen_dict
    for sk, sv in sahen_dict.items():
        sverb = sv['s_verb'][0]
        for ck, cv in combi_dict.items():
            if not sverb in cv['src_sen'].split(' '):
                continue
            dsen = sv['d_sen'][0]
            if cv['dst_sen'] in dsen:
                continue
            tmp_dict[sk]['sentence'].append(cv['dst_sen'].replace(' ', ''))
            tmp_dict[sk]['sentence_space'].append(cv['dst_sen'])
    sahen_dict = tmp_dict
    return sahen_dict

def get_case(sahen_dict, combi_dict):
    tmp_dict = sahen_dict
    for sk, sv in sahen_dict.items():
        sen_list = sv['sentence_space']
        for ck, cv in combi_dict.items():
            if not cv['dst_sen'] in sen_list:
                continue
            dpos = cv['dst_pos'].split(',')
            idx = dpos.index(PARTICLE)
            dsen = cv['dst_sen'].split(' ')
            tmp_dict[sk]['part'].append(dsen[idx])
    sahen_dict = tmp_dict
    return sahen_dict

if __name__ == '__main__':
    chunks = q41.make_chunks('neko.txt.cabocha')
    chunkdict = q42.make_chunkdict(chunks[868])
    combi_dict = q42.make_combidict(chunkdict)
    sahen_dict = make_sahen_pattern(combi_dict)
    sahen_dict = get_verb_depend(sahen_dict, combi_dict)
    sahen_dict = get_case(sahen_dict, combi_dict)
    for k, v in sahen_dict.items():
        print k + '\t' + ' '.join(v['part']) + '\t' + ' '.join(v['sentence']) 
