import sys
import networkx
import operator

from grafon.graphs.plwngraph import PlWNGraph
from grafon.sumo import sumograph
from grafon.sumo import sumoproc

from grafon.mergers import BaseGraphMerger
from grafon.graphs.basegraph import BaseGraph
from grafon.gbuilders.graphbuilder import GraphBuilder

from grafon.filters.posfilter import POSFilter

from grafon.utils.grafonconfig import GrafonConfig


def save_simple_graph_to_file(graph_file_name, graph):
  try:
    A = networkx.to_agraph(graph)
    A.layout(prog='dot', args="-Grankdir=LR")
    # A.layout(prog='sfdp', args='-Goverlap=prism')
    A.draw(graph_file_name)
  except Exception, e:
    print e

def main():
  # konfig....
  cfg = GrafonConfig()
  cfg.read('cfg/grafon.ini')
  
  # sumo graph
  print 'Loading SUMO graph...'
  sumo_graph_file = '/home/pkedzia/repos/plumper/resources/sumo_graph'
  sgraph = sumograph.SumoGraph()
  sgraph.build_graph(sumo_graph_file)

  #input files: ccl and relcll
  cclfile = '/home/pkedzia/repos/saper/sample-texts/wiki-wiki.ccl'
  relcclf = '/home/pkedzia/repos/saper/sample-texts/wiki-wiki.rel.ccl'

  #database config file
  dbcfg_file  = '/mnt/data/repos/grafon/cfg/pkedzia-localhost.db'
  out_pickle = '/home/pkedzia/repos/grafon/resources/plwngraphs/plwn-6.11.2014'
  plwngraph = PlWNGraph()
  print 'Loading plWN graph...'
  if not plwngraph.read_graph(dbcfg_file, out_pickle):
    print "Nie mozna polaczyc z baza!"
    return 1

  tagset = cfg.tagset()

  # filters
  noun_pl_pos = ['subst', 'depr', 'ger']
  adj_pl_pos = ['adj', 'adja', 'adjp', 'adjc']
  verb_pl_pos = ['fin', 'bedzie', 'praet', 'impt', \
                 'inf', 'pcon', 'pant', 'imps', \
                 'winien', 'pred', 'pact', 'ppas', 'pred']
  filter_pos = noun_pl_pos + adj_pl_pos + verb_pl_pos
  filters = [
    POSFilter(tagset, filter_pos)]

  # properties for graph which will be built
  nc = cfg.node(tagset)
  bg = BaseGraph(nc, filters)

  # Mergers
  plwn_mergers = [cfg.plwn_merger(bg)]
  sumo_mergers = [cfg.sumo_merger(bg)]
  
  bgb = GraphBuilder()
  try:
    bgb.build_graph_from_file(bg, cclfile, relcclf, tagset)
  except Exception ,e:
    print "Exception:", e
    return 0

  # dodaje do grafu krawedzie z wykorzystaniem 
  # builderow zadeklarowanych wczesniej
  for ebuilder in cfg.ebuilders():
    if ebuilder:
      ebuilder.add_edges(bg)

  # save graphs into img-files
  all_graphs = []
  for sid, graph in bg.graph_dict.iteritems():
    print 50 * '='
    print 'Building graph for sentence ', sid
    # ---------------------- 
    # zapisuje sobie graf zdania
    graph_file_name = 'png/graph_' + sid + '.png'
    save_simple_graph_to_file(graph_file_name, graph)
    all_graphs.append((sid, graph))
    if len(all_graphs) >= 5:
       break

  bm = BaseGraphMerger(bg)
  g1 = all_graphs[0]
  g2 = all_graphs[1]
  mg = bm.merge(g1[1], g2[1])
  for i in range(2, len(all_graphs)):
    print '...merging with', all_graphs[i][0]
    mg = bm.merge(mg, all_graphs[i][1])
  
  print 'Saving merged graphs into file'
  save_simple_graph_to_file('png/merged-sentence-graphs.png', mg)

  sumo_merger = cfg.sumo_merger(bg)
  plwn_merger = cfg.plwn_merger(bg)
  for gk, graph in all_graphs:
    print 'Processing and merging with', gk
    
    print '\tsenses...'
    senses = sumoproc.get_senses_from_nxgraph(graph)
    in_text = senses.keys()
    sense_sub = plwngraph.all_minimal_subgraphs(in_text)[0]
    plwn_merger.merge(mg, sense_sub)
    save_simple_graph_to_file('png/graph_' + gk + '-plwn.png', sense_sub)

    print '\tconcepts...'
    concepts  = sumoproc.get_concepts_from_nxgraph(graph)
    in_text = concepts.keys()
    concep_sub = sgraph.all_minimal_subgraphs(in_text)[0]
    sumo_merger.merge(mg, concep_sub)
    save_simple_graph_to_file('png/graph_' + gk + '-sumo.png', concep_sub)

  # print 'Saving all merged graphs into one file'
  # save_simple_graph_to_file('png/merged-all-with-sumo.png', mg)
  
  # masures
  measures = cfg.measures()
  print >> sys.stderr, 'S1; S2; ',
  for m in measures:
    print >> sys.stderr, m, ';',
  print >> sys.stderr, ''
  
  print 'Measures....'
  # calcullate measures
  for gnum1, g1 in enumerate(all_graphs):
    for gnum2 in range(gnum1 + 1, len(all_graphs)):
      g2 = all_graphs[gnum2]
      print >> sys.stderr, g1[0], ';', g2[0], ';', 
      for m in measures:
        v = m.calculate(g1[1], g2[1])
        print >> sys.stderr, v, ';',
        print g1[0], g2[0], m, v
      print >> sys.stderr, ''
      print 10 * '-'

  # print sentences
  for snmb, msub in all_graphs:
    for p in bg.document.paragraphs():
      for s in p.sentences():
        if s.id() == snmb:
          print snmb + ':', ' '.join(t.orth_utf8() for t in s.tokens())
          print >> sys.stderr, snmb + ';', '"' + \
            ' '.join(t.orth_utf8() for t in s.tokens()) + '"'

if __name__ == '__main__':
    main()
