# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA

import tginvoice, os

ex_dir = os.path.join(os.path.dirname(tginvoice.__file__), 'examples')

from tginvoice.utils.standard import ADD_TYPES

__usage__ = _(u"%s add TYPE [OPTIONS] path/to/file.csv ")

__summary__ = _(u"Add data to database from csv file")

__description__ = _(u"""
Available TYPEs are:
""")

for t in ADD_TYPES:
    __description__ = "%s\t%s\n"%(__description__,t)

__examples__ = ("""
# tginvoice-admin add biller %s
# tginvoice-admin add customer %s
"""%(ex_dir+'/biller.csv', ex_dir+'/customers.csv'))





def get_parser(loader):
    parser = loader.OptionParser(usage=__usage__%(loader.APPNAME),
            description="%s\n%s"%(__summary__,__description__),
            examples=__examples__,
            )
    parser.add_option("-d", "--debug", action="store_true", dest="debug",
            help="Log level debug"),
    parser.add_option("-c", "--csv",  dest="csv",
            help="Use csv file"),
    return parser

def usage(loader):
    return get_parser(loader).print_help()

def main(loader):
    import sys, os
    options, args = get_parser(loader).parse_args(loader.sys.argv)
    args = args[2:]

    if options.debug:
        loglevel = 'DEBUG'
    else:
        loglevel = 'INFO'

    if len(args) >= 1:
        type_name = args[0]
        csv_path = options.csv
        tables = loader.tables
        tables.metadata.create_all(checkfirst=True)

        if type_name in ADD_TYPES:
            if csv_path:
                if os.path.exists(csv_path):
                    import csv
                    csv_lst= csv.reader(open(csv_path))
                    index = 0
                    col_lst = []

                    for row in csv_lst:
                        if index == 0:
                            col_lst = row
                        else:
                            values = {}
                            for col_index in range(len(col_lst)):
                                values[col_lst[col_index]] = row[col_index]
                            try:
                                loader.insert.insert_table(loader, type_name, **values)
                            except:
                                raise
                        index += 1

                    sys.exit()
                else:
                    sys.stderr.write('CSV file `%s` does not exist\n'%(csv_path))
                    sys.exit(1)
                #loader._set_engine()

                for row in csv:
                    values = {}
                    for index in range(len(loader.standard.composizione_richiesta)):
                        values[loader.standard.composizione_richiesta[index]]=row[index]
                    #import sys; sys.exit()
                    try:
                        loader.insert.insert_table(loader, 'composizione_richiesta', **values)
                        #loader.tables.session.commit()
                    except:
                        raise
            else:
                form_lst = []
                form_map = []
                values = {}

                if type_name == 'user':
                    form_lst = loader.standard.USER_FORM
                    form_map = loader.standard.USER_MAP

                for item in form_lst:
                    values[str(item)] = raw_input("%s: "%form_map[item])

                try:
                    loader.insert.insert_table(loader, type_name, **values)
                except:
                    raise






    else:
        usage(loader)



