#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ABOUT THIS SCRIPT:

Import CSV data files as tables into Scribus

1. Create a table frame with the desired size and positioned 
where you want the table to be located

2. Make sure it is selected

3. Execute this script:

4. Resize the table to fix it's appearance

You will be prompted for a csv filename

4. The data from the csv file will be imported and a table will be drawn on the page.

LIMITATIONS:

1.

2.

HINTS:

Postgresql:
You can easily create a CSV file with a Postgresql database. From Postgresql,
toggle unaligned output with the '\a' switch, then activate a comma as
a separator with '\f ,' (without apostrophes). Send output to a file
with '\o myfile.csv', then query your database.

Sqlite3:
You can use "sqlite3 -csv" in the command line or ".mode csv" in sqlite's
interactive shell.

############################

LICENSE:

This program 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 of the License, or
(at your option) any later version.

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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Author: Sebastian Stetter

Modifications: Gregory Pittman, Clinton Reese

please report bugs to: scribusscript@sebastianstetter.de
"""

from __future__ import division
import sys

try:
    # Please do not use 'from scribus import *' . If you must use a 'from import',
    # Do so _after_ the 'import scribus' and only import the names you need, such
    # as commonly used constants.
    import scribus
except ImportError as err:
    print ("This Python script is written for the Scribus scripting interface.")
    print ("It can only be run from within Scribus.")
    sys.exit(1)

#########################
# YOUR IMPORTS GO HERE  #
#########################
import csv

#get information about the area where the table should be drawn
def getTableProperties():
    table_info = dict()
    if scribus.selectionCount() == 1:
        areaname = scribus.getSelectedObject()
        objtype=scribus.getObjectType(areaname)
        if objtype != "Table":
            scribus.messageBox("csv2table", "selection must be a table")
            sys.exit()
        position= scribus.getPosition(areaname)

        table_info["name"] = areaname
        table_info["vpos"] = position[1]
        table_info["hpos"] = position[0]
        #size not the same as height width
        #size = scribus.getSize(areaname)
        #table_info["xsize"] = size[0]
        #table_info["ysize"] = size[1]
        table_info["column_count"] = scribus.getProperty(areaname, "columns")
        table_info["row_count"] = scribus.getProperty(areaname, "rows")

        return table_info
        
    else: 
        scribus.messageBox("csv2table", "please select ONE Table to mark the drawing area for the table")
        sys.exit()

#get the cvs data
def getCSVdata():
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(open(csvfile, "r"))
            datalist=[]
            for row in reader:
                rowlist=[]
                for col in row:
                    rowlist.append(col)
                datalist.append(rowlist)
            return datalist
        except Exception as e:
            scribus.messageBox("csv2table", "Could not open file %s"%e)
    else:
        sys.exit

def getDataInformation(list):
    """takes a 2 dimensional list object and returns the numbers of rows and cols"""
    datainfo = dict()
    datainfo["rowcount"]=len(list)
    datainfo["colcount"]= len(list[0])
    return datainfo
    
def main(argv):
    """This is a documentation string. Write a description of what your code
    does here. You should generally put documentation strings ("docstrings")
    on all your Python functions."""
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    if not scribus.haveDoc() > 0: #do we have a doc?
        scribus.messageBox("importcvs2table", "No opened document.\nPlease open one first.")
        sys.exit()

    table_props = getTableProperties()

    data = getCSVdata()
    di = getDataInformation(data)

    # resize the table counts to fit the imported data

    delta_col = di["colcount"] - table_props["column_count"]
    delta_row = di["rowcount"] - table_props["row_count"]

    if delta_col > 0:
        scribus.insertTableColumns(0, delta_col)
    if delta_col < 0:
        delta_col = delta_col * -1
        scribus.removeTableColumns(0, delta_col)

    if delta_row > 0:
        scribus.insertTableRows(0, delta_row)
    if delta_row < 0:
        delta_row = delta_row * -1
        scribus.removeTableRows(0, delta_row)
    
    i=0
    scribus.progressTotal(len(data))

    rowindex=0
    
    for row in data:
        c=0
        colindex=0
        for cell in row:
            cell = cell.strip()
            scribus.setCellText(rowindex, colindex, cell, table_props["name"])
            c=1
            colindex=colindex+1

        i=i+1
        scribus.progressSet(i)
        rowindex=rowindex+1
    
    scribus.messageBox("importcvs2table", "Resize the table to fix the appearance.")

    scribus.progressReset()
    scribus.docChanged(True)
    scribus.statusMessage("Done")


def main_wrapper(argv):
    """The main_wrapper() function disables redrawing, sets a sensible generic
    status bar message, and optionally sets up the progress bar. It then runs
    the main() function. Once everything finishes it cleans up after the main()
    function, making sure everything is sane before the script terminates."""
    try:
        scribus.statusMessage("Importing .csv table...")
        scribus.progressReset()
        main(argv)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc() > 0:
            scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()

# This code detects if the script is being run as a script, or imported as a module.
# It only runs main() if being run as a script. This permits you to import your script
# and control it manually for debugging.
if __name__ == '__main__':
    main_wrapper(sys.argv)
