#!/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__ = '''Narzędzie służy do rozbijania decyzji wieloklasowej w wejściwym 
pliku na wiele pojedynczych decyzji. Czyli jeśli użytkownik miał oceniać
czy między daną parą zdań zachodzą relacje r1, r2, r3 to podawał decyzje:
t/n, t/n, t/n. A skrypt ten powoduje rozbicie na r1->t/n itd.
'''

import os, sys
import csv, argparse
try:
  import argcomplete
except ImportError:
  argcomplete = None

def make_parser(desc = ''):
  aparser = argparse.ArgumentParser(description = desc)
  aparser.add_argument(
    '-i', '--input-decisions-file', dest='in_dec_file', 
    required=True, type=str, help=('File with user decisions.'))
  aparser.add_argument(
    '-o', '--output-decisions-file', dest='out_dec_file', 
    required=True, type=str, help=('File with split user decisions.'))
  if argcomplete:
    argcomplete.autocomplete(aparser)
  return aparser

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

  with open(args.out_dec_file, 'wt') as ofile:
    with open(args.in_dec_file) as infile:
      first_line = True
      spamreader = csv.reader(infile, delimiter='\t', quotechar='|')
      for row in spamreader:
        if first_line:
          first_line = False
          continue

        rels = [r.strip() for r in row[4].split(',')]
        decs = [b for b in [d.strip().split(',') for d in row[5:]]]
        decisions = []
        for d in decs:
          while len(d) < len(rels):
            d.append('t')
          decisions.append(d)

        '''
        if len(rels) > 1:
          print row
          print len(rels), decisions, zip(*decisions)
        '''
        rdec = zip(*decisions)

        for i, r in enumerate(rels):
          ofile.write('%s\t%s\t"%s"\t"%s"\t%s' % (row[0], row[1], row[2], row[3], r))
          for d in rdec[i]:
            ofile.write('\t%s' % d.strip())
          ofile.write('\n')

if __name__ == '__main__':
  main()