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

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

import os
import zipfile
import cgi
import sqlite3

import sys
sys.path.append("/home/strubi/doc/develop/components")

import partdb

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 "<br>"
print ' - <a href="?cmd=scan">Library-Dateien nach Symbolnamen abscannen</a>'
print "<br>"
print ' - <a href="?cmd=scanmod">Module-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>"



# Get the symbol names of the lib file
def scan_lib(fname, f, symbollist):
	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 symbollist


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

#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

def list_syms(symlist):
	print '<h2>Gefundene Symbole:</h2>'

	print '<p>Anzahl Symbole: %i</p>' % len(symlist)
	
	print '<h3>Liste:</h3>'
	for i,s in enumerate(sorted(symlist)):
		print s, '|', 
	print '<br>'
	
	print '<h3>Dateizuordnung:</h3><ul>'
	for i,s in enumerate(sorted(symlist)):
		print '<li><b>', s, '</b>',
		if len(symlist[s]) > 0: #Set to one to get only double occurences
			print '(' + ' - '.join(symlist[s]) + ')'
		print '</li>'
	print '</ul>'


def scan_files(filext, handler):
	symlist = {}
	for root, dirs, files in os.walk(Librarybase):
		for f in files:
			fname = root + '/' + f
			if f.endswith(filext):
				print root + '/<b>' + f, '</b>'
				print 'OK' if handler(fname, open(fname).read(), symlist) 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(filext):
						ms = sanitized(m)
						print '<li><b>', ms, '</b>'
						print 'OK' if handler(fname + '/' + ms, z.read(m), symlist) else 'Error'
						print '</li>'
				print '</ul>'
	return symlist


#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>'

	libsyms = scan_files(".lib", scan_lib)
	list_syms(libsyms)

	p = partdb.PartDB()
	try:
		p.add_parts(libsyms)
		print '<b>Added parts to part-db</b>'
	except:
		print '<b>Failed to add parts to part-db</b>'
		print '<p>Error: %s</p>' % sys.exc_info()[1]


elif cmd == 'scanmod':
	print '<h2>Scanning...</h2>'

	modsyms = scan_files(".mod", scan_mod)
	list_syms(modsyms)

	p = partdb.PartDB()
	try:
		p.add_footprints(modsyms)
		print '<b>Added footprints to part-db</b>'
	except:
		print '<b>Failed to add footprints to part-db</b>'
		print '<p>Error: %s</p>' % sys.exc_info()[1]


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

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

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