#! /usr/bin/env python3
#
# version 5, Caspar Verhey 2017
#
# 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 first row, containing only column titles

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

    try:
        open(outputfile)
    except FileNotFoundError:
        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][4:6]+'/'+row[0][6:8]+'/'+row[0][0:4] # Datum, converteren van YYYYMMDD naar DD-MM-YY
      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" ): # Af/Bij
        in_bedrag = str(row[6]) # Bedrag (EUR)
      else:
        in_bedrag = '-' + str(row[6]) # Af/Bij & Bedrag (EUR)

      in_soort    = row[7] # MutatieSoort
      in_mededl   = ' '.join(row[8].split()) # Mededelingen
      
      # HomeBank CSV format
      # Column list:
      # date ; payment mode ; info ; payee ; memo ; amount ; category ; tags
      #
      # Values:
      # date     => format should be DD-MM-YY (CV NOTE: didn't work, it seems to expect MM/DD/YYYY)
      # payment mode  => 0 = None; 1 = Credit Card; 2 = Check; 3 = Cash; 4 = Transfer; 5 = Internal Transfer; 6 = Debit Card; 7 = Standing Order; 8 = Electronic Payment; 9 = Deposit; 10 = Financial Institutions fee (transaction fees etc.); 11 = Direct Debit
      # info     => a string
      # payee    => a payee name
      # memo     => a string
      # amount   => a number with a '.' or ',' as decimal separator, ex: -24.12 or 36,75
      # category => a full category name (category, or category:subcategory)
      # tags	   => tags separated by space (mandatory since HomeBank v4.5)
      #
      # Example:
      #
      # 15-02-04;0;;;Some cash;-40,00;Bill:Withdrawal of cash;tag1
      # 15-02-04;1;;;Internet DSL;-45,00;Inline service/Internet;tag2
      # ...
      
      out_date   = in_datum
      out_paymod = self.ingCode2homeBankPaymentMode(in_code)

      if (in_code == 'DV') and (in_tegreknr == '') and ('INCASSO CREDITCARD ' in in_naam):
          out_paymod = 1 # detect credit card payments; they don't have a specific code in ING's CSV

      out_info   = in_code
      
      if(in_tegreknr == ''):
          out_payee = in_naam
      else:
          out_payee = in_naam + ' ['+in_tegreknr+']'
          
      out_desc   = in_mededl
      out_amount = in_bedrag
      out_cat    = ''
      out_tag    = ''
      
      out_row = [ out_date, out_paymod, "'"+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 ingCode2homeBankPaymentMode(self, x):
      return {
          'AC': 4,
          'IC': 11,
          'BA': 6,
          'OV': 4,
          'PK': 3,
          'FL': 4,
          'PO': 7,
          'GF': 8,
          'ST': 9,
          'GM': 3,
          'VZ': 4,
          'GT': 8,
      }.get(x, 0)
      
      # ING CSV format code => translation to HomeBank payment mode field
      #
      # AC = Acceptgiro => 4 = Transfer
      # IC = Incasso => 11 = Direct Debit
      # BA = Betaalautomaat => 6 = Debit card
      # OV = Overschrijving => 4 = Transfer
      # DV = Diversen => 0 = no payment type assigned
      # PK = Opname kantoor => 3 = Cash
      # FL = Filiaalboeking => 4 = Transfer
      # PO = Periodieke overschrijving => 7 = Standing Order
      # GF = Telefonisch bankieren => 8 = Electronic Payment
      # ST = Storting => 9 = Deposit
      # GM = Geldautomaat => 3 = Cash
      # VZ = Verzamelbetaling => 4 = Transfer
      # GT = Internet bankieren => 8 = Electronic Payment
         
  def printhelp(self):
    print("Usage: ./homebankcsv.py <inputfile> [<outputfile>]\n\nConverts a CSV-file generated by ING Bank (https://mijn.ing.nl/) to a CSV-file supported by HomeBank (http://homebank.free.fr/).\n\n\t<inputfile>\tING Bank CSV filename\n\t<outputfile>\tHomeBank CSV filename, defaults to output.csv\n\t-?, -h, --help\tdisplay this help and exit\n\nVersion 5. Report bugs to caspar@verhey.net.\n")
    
if __name__ == "__main__":
    Convert(sys.argv)
