#!/usr/bin/python3

import os
import glob

# Open (create if not exists) file, truncate and write csv header
csv=open("book.csv","w+")
csv.truncate(0)
csv.write('org;fullname;street;city;zip\n')

# Parse all contacts
for file in glob.glob('./contacts/*/*.vcf'):
  
  # Empty variables to get rid of relicts from previous files
  fn = po_box = ext_address = street = city = region = zip = country = org = ""

  for line in open(file):
    if "FN:" in line:
      print(file)
      print(line)
      fn=line.rstrip().replace("FN:","")
      continue
    if "ADR;" in line:
      print(line)
      adr=line.rstrip().split(':', 1)[-1].split(';')
      po_box=adr[0]
      ext_address=adr[1]
      street=adr[2]
      city=adr[3]
      region=adr[4]
      zip=str(adr[5])
      country=adr[6]
      continue
    if "ORG:" in line:
      print(line)
      org=str(line.rstrip().replace("ORG:","").split(';')[0])
      continue
    
  if len(org) > 0:
    csv.write(org+';'+fn+';'+street+';'+city+';'+zip+'\n')
    
csv.close()