# Copyright (c) 2012 by Zuse-Institute Berlin and the Technical University of Denmark.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#     3. Neither the name of the copyright holders nor contributors may not
#        be used to endorse or promote products derived from this software
#        without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS NOR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# Direct execution requires top level directory on python path                          
if __name__ == "__main__":
  import os, sys, inspect
  scriptdir = os.path.split(inspect.getfile( inspect.currentframe() ))[0]
  packagedir = os.path.realpath(os.path.abspath(os.path.join(scriptdir,'..')))
  if packagedir not in sys.path:
    sys.path.insert(0, packagedir)


import re, csv, textwrap, os, sys, inspect, gzip
from data.BIBdata import BIBdata

def autogen_tags_writer(f, name, csvdata, bibdata):
  row = None
  for r in csvdata:
    if r[0].find(name) != -1:
      row = r
      break

  if not row:
    raise Exception(''.join(['Instance named "', name, '" not found in ref.csv.\n']))

  wrapwidth = 78
  text = list()

  # Get contributor
  text.append(''.join(['Contributor: ', row[1]]))

  # Get description
  text.extend(textwrap.wrap(row[3], wrapwidth))

  # Get detail
  if len(row[4].strip()) >= 1:
    text.append('')
    text.extend(textwrap.wrap(row[4], wrapwidth))

  # Get references
  for key in row[2].split(','):
    key = key.strip()
    text.append('')
    text.extend(bibdata.get(key).split('\n'))

  f.write('# ' + '\n# '.join(text) + '\n')


def update_autogen_tags(files):
  # Find the directory of this script
  scriptdir = os.path.split(inspect.getfile( inspect.currentframe() ))[0]
  rootdir = os.path.join(scriptdir,'..','..')

  # Define 'bibdata'
  bibpath = os.path.join(rootdir,'instances','ref.bib')
  bibdata = BIBdata(bibpath)

  # Define 'csvdata'
  csvpath = os.path.join(rootdir,'instances','ref.csv')
  csvfile = open(csvpath, 'rt')
  try:
    csvreader = csv.reader(csvfile, delimiter=';', quotechar='"')
    next(csvreader)
    csvdata = list(csvreader)
  finally:
    csvfile.close()

  # Define 'tagpattern':
  #  (1) Pattern starts with file or after newline
  #  (2) Anything may follow except a newline
  #  (3) Then comes <CBLIB:AUTOGEN>
  #  (4) Anything may follow
  #  (5) Then comes </CBLIB:AUTOGEN>
  #  (6) Anything may follow except a newline
  #  (7) Pattern ends after newline
  tagpattern = re.compile('^.*<CBLIB:AUTOGEN>[\s\S]*</CBLIB:AUTOGEN>.*\\n', re.MULTILINE)

  # Search files in benchmark library
  # if len(files) = 0:
  #  for dirpath, dirnames, filenames in os.walk(os.path.realpath(os.path.abspath(os.path.join(rootdir,'instances','cbf'))) ):
  #    filenames.sort()
  #    for filename in filenames:
  #      if os.path.splitext(filename)[1] == '.cbf':
  #        files.append(os.path.join(dirpath,filename))

  # Update instances
  for file in files:
    print(file)
    [instancename, filetype] = os.path.splitext(os.path.basename(file))
    instancenaem = os.path.basename(instancename)

    if filetype.lower() == '.gz':
      instancename = os.path.splitext(instancename)[0]
      f = gzip.open(file,'r')
    else:
      f = open(file,'r')

    try:
      instancedata = f.read()
      instancedata = tagpattern.sub('', instancedata)
    finally:
      f.close()

    if filetype.lower() == '.gz':
      f = gzip.open(file,'wb')
    else:
      f = open(file,'wb')

    try:
      f.write('#<CBLIB:AUTOGEN>\n')
      autogen_tags_writer(f, instancename, csvdata, bibdata)
      f.write('#</CBLIB:AUTOGEN>\n')
      f.write(instancedata)
    finally:
      f.close()


if __name__ == "__main__":
  try:
    if len(sys.argv) <= 1:
      raise Exception('Incorrect usage, please specify instances to update.')

    update_autogen_tags(sys.argv[1:])

  except Exception as e:
    print(str(e))


