#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2006 Stas Zykiewicz <stas.zytkiewicz@gmail.com>
#
#           MT_users2csv.py
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public License
# as published by the Free Software Foundation.  A copy of this license should
# be included in the file GPL-2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.



"""This is a simple script that turn the values from the multiTable plugin
into a CSV list suitable for importing in a database.
From there the data can printed or whatever.
This is mainly intended for teachers who want to use multiTable as a tool to
track the childrens progress.

Usage: MT_users2csv.py mt_users
The path is optional.
The csv is saved into the current directory when no path is given.
"""

import os,sys,pickle,time
import CPConstants

print __doc__

USERSFILE = os.path.join(CPConstants.HOMEDIR,'multiTables','mt_users')
# print USERSFILE
DESTFILE = os.path.join(CPConstants.HOMEDIR,'mt_users-%s.csv' % 
                                time.strftime("%y_%m_%d-%H%M%S",time.localtime()))
# print DESTFILE

if not os.path.exists(USERSFILE):
    print "Can't find the users file in %s" % USERSFILE
    
def _fetch_sheet():
    """ Load the users file, makes a default sheet when the load fails."""
    try:
        f = open(USERSFILE,'r')
        sheet = pickle.load(f)
        f.close()
    except (IOError,EOFError),info:
        print info
        print >> sys.stderr,'Error in fetching users file'
        print >> sys.stderr,info
        sys.exit(1)
    return sheet

if __name__ == '__main__':
    csv = []
    sheet = _fetch_sheet()
    for user,dic in sheet.items():
        # split the dic in tables and others.
        # the key for a table is always a str(int) so we test for int(key)
        # when it fails it belongs to other, otherwise it will be a table
        others = []
        tables = []
        for k,v in dic.items():
            try:
                int(k)
            except ValueError:
                others.append((k,v))
            else:
                tables.append(('%2s' % k,str(v[1])))
        tables.sort()
        table_times = []
        for item in tables:
            table_times.append(item[1])
        others.sort()
        others_vals = []
        for item in others:
            others_vals.append(str(item[1]))
        csv.append(['"%s"' % user]+table_times+others_vals)
    
    try:
        f = open(DESTFILE,'w')
    except IOError,info:
        print info
        sys.exit(1)
    for line in csv:
        #print line
        l = ','.join(line)
        f.write(l+'\n')
    f.close()


