#!/usr/bin/python3
#
# version 1, Caspar Verhey 2011
#
# http://caspar.verhey.net
#
import sys
import csv

class Convert():

  def __init__(self, argv):

    if( len(argv) < 2 or len(argv) > 3 or '-h' in argv or '-?' in argv or '--help' in argv):
      self.printhelp()
      return
    
    try:
      inputReader = csv.reader(open(argv[1]), delimiter=',', quotechar='"')
    except IOError:
      print("No such file or directory: '" + argv[1] + "'")
      return

    next(inputReader) # skip header

    outputfile = 'output.csv'
    if( len(argv) == 3 ):
      outputfile = argv[2]

    try:
      open(outputfile)
    except IOError:
      pass
    else:
      answer = input('Output file ' + outputfile + ' already exists. Would you like to overwrite it? [y/N] ')
      if not answer:
        return
      if answer not in ['y', 'Y', 'yes', 'Yes', 'j', 'J', 'ja', 'Ja']:
        return
      
    outputWriter = csv.writer(open(outputfile, 'w'), delimiter=';', quotechar='"')

    count = 0
    
    for row in inputReader:
      
      in_datum    = row[0]         # Datum
      in_naam     = ' '.join(row[1].split()) # Naam / Omschrijving
      in_reknr    = row[2]         # Rekening
      in_tegreknr = row[3]         # Tegenrekening
      in_code     = row[4]         # Code

      if( row[5] == "Bij" ):
        in_bedrag = str(row[6]).replace(",",".")
      else:
        in_bedrag = '-' + str(row[6]).replace(",",".")

      in_soort    = row[7]         # MutatieSoort
      in_mededl   = ' '.join(row[8].split()) # Mededelingen
      
      
      out_date   = in_datum
      out_mode   = ''
      out_info   = in_code
      out_payee  = ''
      out_desc   = in_tegreknr + ' - ' + in_naam + ' ' + in_mededl
      out_amount = in_bedrag
      out_cat    = ''
      out_tag    = ''
      
      out_row = [ out_date, out_mode, out_info, out_payee, out_desc, out_amount, out_cat, out_tag ]
      outputWriter.writerow(out_row)
      
      count = count + 1
    
    print(str(count) + ' transactions processed')
    print('read from ' + argv[1])
    print('written to ' + outputfile)
    
  def printhelp(self):
    print("Usage: ./homebankcsv.py <inputfile> [<outputfile>]\n\nConverts a CSV-file generated by the ING Bank to a CSV-file supported by the GNU program HomeBank.\n\n\t<inputfile>\tING Bank CSV filename\n\t<outputfile>\toutput CSV filename, defaults to homebank.csv\n\t-?, -h, --help\tdisplay this help and exit\n\nReport bugs to caspar.verhey.net")
    
if __name__ == "__main__":
    Convert(sys.argv)

# Column list:
# date ; paymode ; info ; payee ; description ; amount ; category
#
# Values:
# date     => format should be DD-MM-YY
# mode     => from 0=none to 10=FI fee
# info     => a string
# payee    => a payee name
# description  => a string
# amount   => a number with a '.' as decimal separator, ex: -24.12 or 36.75
# category => a full category name (category, or category:subcategory)
#
# Example:
#
# 15-02-04;0;;;Some cash;-40,00;Bill:Withdrawal of cash
# 15-02-04;1;;;Internet DSL;-45,00;Inline service/Internet
