#!/usr/bin/python
# -*- coding: utf8 -*-
#======================================================================
#Basisverzeichnis der Library-Dateien hier einstellen.
#Es MUSS als Unterverzeichnis im Pfad des Server-Verzeichnisses liegen.
Librarybase = u'kicadlib.org/'   # Am Ende muss ein '/' stehen.

#======================================================================

import os
import zipfile
import cgi
import sqlite3

f = cgi.FieldStorage()
cmd = f.getfirst('cmd', None)
showimg = f.getfirst('showimg', False)
if showimg: showimg = True

db = sqlite3.connect('KiCad.sqlite3')
c = db.cursor()
c.execute('CREATE TABLE IF NOT EXISTS symbols (filename TEXT, datetime TEXT, symbol TEXT)')

print """Content-type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
<title>KiCad Library-Verwaltung</title>
</head>
<body>
<h1>KiCad Library-Verwaltung</h1>"""

print "Server-Basisverzeichnis: %s<br>Library-Basisverzeichnis: %s<br>" % (os.getcwd(), Librarybase)

print 'Befehle:'
print '<a href="?cmd=show">Dateien anzeigen</a> (<a href="?cmd=show&showimg=Y">mit Bildern</a>)'
print ' - <a href="?cmd=scan">Library-Dateien nach Symbolnamen abscannen</a>'
#print ' - <a href="?cmd=listfiles">In DB eingelesene Library-Dateien auflisten</a>'
#print ' - <a href="?cmd=listsymbols">Symbole in DB auflisten</a>'

print "<hr>"


symbollist = {}

# Get the symbol names of the lib file
def scanfile(fname, f):
	print len(f), 'Bytes'
	for line in f.split('\n'):
		if line.startswith('DEF '):
			symbolname = line.split(' ')[1]
			if symbolname not in symbollist:
				symbollist[symbolname] = [fname]
			else:
				symbollist[symbolname].append(fname)
			print '-', '<span style="color:blue"><b>', symbolname, '</b></span>'
	return True

#hack to circumvent filename codings in zip files which create problems
def sanitized(s): 
	try:
		s2 = s.encode('utf8')
	except:
		s2 = ''
		for c in s:
			if c.isalpha():
				s2 += c
			else:
				s2 += '?'
	return s2

#Selector for user commands
if cmd == 'show':
	for root, dirs, files in os.walk(Librarybase):
		for f in files:
			print root + '/' + f, '<br>'
			if showimg and (f.endswith('.png') or f.endswith('.jpg')):
				print '<img src="' + '/' + root + '/' + f + '"><br>'
			elif f.endswith('.zip'):
				print '<ul>'
				for m in zipfile.ZipFile(root + '/' + f, 'r').namelist():
					print '<li>', m, '</li>'
				print '</ul>'

if cmd == 'scan':
	print '<h2>Scanning...</h2>'
	for root, dirs, files in os.walk(Librarybase):
		for f in files:
			fname = root + '/' + f
			if f.endswith('.lib'):
				print root + '/<b>' + f, '</b>'
				print 'OK' if scanfile(fname, open(fname).read()) else 'Error'
				print '<br>'
			elif f.endswith('.zip'):
				print root + '/' + f, '<br>'
				print '<ul>'
				z = zipfile.ZipFile(fname, 'r')
				for m in z.namelist():
					if m.endswith('.lib'):
						ms = sanitized(m)
						print '<li><b>', ms, '</b>'
						print 'OK' if scanfile(fname + '/' + ms, z.read(m)) else 'Error'
						print '</li>'
				print '</ul>'
	print '<h2>Gefundene Symbole:</h2>'
	print 'Anzahl Symbole: %i<br>' % len(symbollist)
	
	print '<h3>Liste:</h3>'
	for i,s in enumerate(sorted(symbollist)):
		print s, '|', 
	print '<br>'
	
	print '<h3>Dateizuordnung:</h3><ul>'
	for i,s in enumerate(sorted(symbollist)):
		print '<li><b>', s, '</b>',
		if len(symbollist[s]) > 0: #Set to one to get only double occurences
			print '(' + ' - '.join(symbollist[s]) + ')'
		print '</li>'
	print '</ul>'

elif cmd == 'listfiles':
	pass #Not implemented

elif cmd == 'listsymbols':
	pass #Not implemented

print """<hr>
</body>
</hmtl>
"""
