# Run this to get output csv files that can be imported into Libib
# code quality is meh and isn't really robust; only to help get you started
#===============================================
# fill these up with the input Shelfari csv file and the output directory 
outPath 		= FILL_ME_UP
shelfariFile 	= FILL_ME_UP
#===============================================

import csv

def write( dicts, filename ):
	with open( filename, "wb" ) as csvOut:
		csvWriter = csv.writer( csvOut )
		
		# for debugging
		# csvWriter.writerow( dicts[ 0 ].keys() ) 
		# for book in dicts:
			# csvWriter.writerow( book.values() )
		
		csvWriter.writerow( [ "ISBN", "Title", "My Rating", "Tags"  ] )
		for book in dicts:
			csvWriter.writerow( [ book[ "ISBN" ], book[ "Title" ], book[ "My Rating" ], book[ "Tags" ] ] )

def getTags( book ):
	tags = [ "Owned", "Favorite", "Wishlist", "Plan To Read", "Currently Reading", "Read" ]
	tagString = ""
	for tag in tags:
		tagString += tag + "," if book[ tag ] == "True" else ""


	return tagString.rstrip( ',' )


with open( shelfariFile, "rb" ) as booksCSV:
	booksReader = csv.reader( booksCSV )#, delimiter = " ", quotechar = "|" )
	books = [ row for row in booksReader if row ]

header = books[ 0 ]
header += "Tags"
dicts = []
for book in books[1:]:
	bookDict = dict( zip( header, book ) )
	bookDict[ "Tags" ] = getTags( bookDict )
	dicts.append( bookDict )

withoutISBN = filter( lambda x : not x[ "ISBN" ], dicts )
write( withoutISBN, outPath + "withoutISBN.csv" )

dicts = filter( lambda x : x[ "ISBN" ], dicts )
write( dicts, outPath + "library.csv" )

noTag = filter( lambda x : not x[ "Tags" ], dicts )
write( noTag, outPath + "noTag.csv" )