#-*- coding:utf-8 -*-
# author: B.Niton

import os
import codecs

from django.core.management.base import BaseCommand

from dictionary.models import *
from settings import PROJECT_PATH

ASPECT_PAIRS_PATH = os.path.join(PROJECT_PATH, 'data', 'pary_aspektowe.txt')

class Command(BaseCommand):
    help = 'Sets aspect relations from SGJP in system.'

    def handle(self, **options):
        set_aspect_relation()  

def set_aspect_relation():
    Entry.objects.all().delete()
    AspectRelationsGroup.objects.all().delete()
    try:                                 
        with codecs.open(ASPECT_PAIRS_PATH, 'rt', 'utf-8') as infile:
            for line in infile:
                line = line.strip()
                print smart_str(line)
                line_elems_ls = line.split('\t')
                entry1 = line_elems_ls[0].strip()
                entry2 = line_elems_ls[3].strip()
                entry1_in_relation = False
                entry2_in_relation = False
                entry1_obj, xx = Entry.objects.get_or_create(name=entry1)
                entry2_obj, xx = Entry.objects.get_or_create(name=entry2)
                try:
                    aspect_relations_gr = AspectRelationsGroup.objects.get(members__name=entry1)
                    entry1_in_relation = True
                except AspectRelationsGroup.DoesNotExist:
                    pass
                try:
                    aspect_relations_gr = AspectRelationsGroup.objects.get(members__name=entry2)
                    entry2_in_relation = True
                except AspectRelationsGroup.DoesNotExist:
                    pass
                if not entry1_in_relation and not entry2_in_relation:
                    aspect_relations_gr = AspectRelationsGroup()
                    aspect_relations_gr.save()
                    aspect_relations_gr.members.add(entry1_obj)
                    aspect_relations_gr.members.add(entry2_obj)
                elif not entry1_in_relation:
                    aspect_relations_gr.members.add(entry1_obj)
                elif not entry2_in_relation:
                    aspect_relations_gr.members.add(entry2_obj)          
    finally:
        infile.close()
        for group in AspectRelationsGroup.objects.all():
            print smart_str(group)
        
        