#!/usr/bin/python
# -*- coding: utf-8 -*-
#PYTHON_ARGCOMPLETE_OK

# <one line to give the library's name and an idea of what it does.>
# Copyright (C) 2014  <copyright holder> <email>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

__doc__ = """
Uwzględniając paczki lingwistów wyszukuje w nich relacji. Dowolnych.
Wlaściwie, to mierzy podobieństwo wewnatrz nich. Dla każdej miary z osobna
tworzone jest wyjście pokazujące podobieństwo danej miary.
"""

import os, sys
import gentbase
import networkx
from grafon.utils.grafonconfig import GrafonConfig

import argparse
try:
  import argcomplete
except ImportError:
  argcomplete = None

def make_parser(desc = ''):
  aparser = gentbase.make_parser(desc)
  aparser.add_argument('-c', '--cfg', dest='config', required=True, 
                       help=('Grafon config'))
  aparser.add_argument('-o', '--out-dir', dest='out_dir', required=True, 
                 help=('Dictionary where similarity output will be stored.'))
  if argcomplete:
    argcomplete.autocomplete(aparser)
  return aparser




def calculate_pack_sim(measures, gpack, outdir, packname):
  outdir = os.path.join(outdir, packname)
  if not os.path.exists(outdir):
    os.makedirs(outdir)

  print >> sys.stderr, 'Calculating package', packname

  for m in measures:
    outpath = os.path.join(outdir, '{}.csv'.format(m))
    with open(outpath, 'wt') as ofile:
      for dn1, dg1 in gpack.iteritems():
        for dn2, dg2 in gpack.iteritems():
          for gn1, g1 in dg1.iteritems():
            for gn2, g2 in dg2.iteritems():
              if gn1 == gn2:
                continue
              # f file/s sentence
              f1, s1 = gn1.split('#')
              f2, s2 = gn2.split('#')
              f1 = os.path.basename(f1)
              f2 = os.path.basename(f2)
              s1 = s1.replace('.pickle', '')
              s2 = s2.replace('.pickle', '')
              ofile.write('{}:{};{}:{};{}\n'.format(
                f1, s1, f2, s2, m.calculate(g1,g2)))

def main(argv=None):
  p = make_parser(__doc__)
  args = p.parse_args(argv)
  cfg = GrafonConfig(args.config)

  # makes output directory if not exists
  if not os.path.exists(args.out_dir):
    os.makedirs(args.out_dir)

  for packname, pack in read_pack(args.pack_dir).iteritems():
    gpack = make_gpack(packname, pack, args.graphs_dir)
    calculate_pack_sim(cfg.measures(), gpack, args.out_dir, packname)

if __name__ == '__main__':
  main()