#!/usr/bin/env python
#
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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.
#
# GNU Enterprise 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 program; see the file COPYING. If not,
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
# Copyright 2004-2007 Free Software Foundation
#
# FILE:
# pdftable/sample.py
#
# DESCRIPTION:
"""
A sample application showing how to use pdftable
"""

# GNUe Modules
from gnue.common.apps.GClientApp import *
from gnue.common.printing.pdftable import *

#
# Sample
#
# Primay class of this application
#
class Sample(GClientApp):
  VERSION = "1.0.0"
  COMMAND = "sample"
  NAME = "sample"
  USAGE = GClientApp.USAGE
  SUMMARY = """
Generates a sample report using gnue.common.printing.pdftable
"""

  def __init__(self):
    GClientApp.__init__(self)
                                         
  def run(self):    
    # ------------------------------------------------------------------------
    # Create the output file
    # ------------------------------------------------------------------------
    f = open('output.pdf','w')
    writer = pdftable(f)
    
    
    writer.setFullTitle([("Quarterly Sales Report", writer.fontDefs['titleFont']),
                         ('2002 - 2004', writer.fontDefs['title2Font']),
                        ])
                        
    # ========================================================================
    # Main section of the report
    # ========================================================================
    
    # ------------------------------------------------------------------------
    # Define this sections columns
    # ------------------------------------------------------------------------
    writer.addColumn(CENTER,7)
    
    # Loop through creating columns for each quarter
    for q in range(4): # q isn't used 
      # 2002 count and %
      writer.addColumn(RIGHT, 5, leftBorder=.25) 
      writer.addColumn(RIGHT, 7) 
      # 2003 count and %
      writer.addColumn(RIGHT, 5, 
             highlight=colors.Whiter(writer.highlightColor,.3)) 
      writer.addColumn(RIGHT, 7, 
             highlight=colors.Whiter(writer.highlightColor,.3))
      # 2004 count and %
      writer.addColumn(RIGHT, 5) 
      writer.addColumn(RIGHT, 7) 

    # ------------------------------------------------------------------------
    # Populate this section's header
    # ------------------------------------------------------------------------        
    
    # Quarter heading 
    writer.addHeader('Q1',CENTER,startColumn=1, endColumn=6)
    writer.addHeader('Q2',CENTER,startColumn=7, endColumn=12, leftBorder=.25)
    writer.addHeader('Q3',CENTER,startColumn=13,endColumn=18, leftBorder=.25, rightBorder=.25)
    writer.addHeader('Q4',CENTER,startColumn=19,endColumn=24)
    
    # Repeating year columns    
    writer.addHeaderRow()
    
    for q in range(4):    
      offset=q*6 # Adjust for 3 years, 2 columns per year for each quarter
      writer.addHeader("2002" , CENTER , 1+offset, 2+offset)
      writer.addHeader("2003" , CENTER , 3+offset, 4+offset)
      writer.addHeader("2004" , CENTER , 5+offset, 6+offset) 

    # The count and % columns            
    writer.addHeaderRow()
        
    writer.addHeader("Model",CENTER,0,0, rightBorder=.25)
    for q in range(4):
      offset=q*6  # Adjust for 3 years, 2 columns per year for each quarter
      print offset
      writer.addHeader('#',CENTER, 1+offset,1+offset)      
      writer.addHeader('%',CENTER, 2+offset,2+offset)
      writer.addHeader('#',CENTER, 3+offset,3+offset)      
      writer.addHeader('%',CENTER, 4+offset,4+offset)
      writer.addHeader('#',CENTER, 5+offset,5+offset)      
      writer.addHeader('%',CENTER, 6+offset,6+offset)

    # ========================================================================
    # Second section of the report
    # ========================================================================
    
    # ------------------------------------------------------------------------
    # Define this sections columns
    # ------------------------------------------------------------------------
    for counter in range(4):
      writer.addColumn(LEFT, 5, sectionType="topSales")
      writer.addColumn(LEFT, 15, sectionType="topSales")
    
    # ------------------------------------------------------------------------
    # Populate this section's header
    # ------------------------------------------------------------------------        
    writer.addHeader('Q1',CENTER, 0, 1, rightBorder=.25, sectionType="topSales")
    writer.addHeader('Q2',CENTER, 2, 3, rightBorder=.25, sectionType="topSales")
    writer.addHeader('Q3',CENTER, 4, 5, rightBorder=.25, sectionType="topSales")
    writer.addHeader('Q4',CENTER, 6, 7, sectionType="topSales")
     
    writer.addHeaderRow(sectionType="topSales")
    writer.addHeader('Year',LEFT,0,0,sectionType="topSales")
    writer.addHeader('Salesperson',LEFT,1,1,sectionType="topSales")
    writer.addHeader('Year',LEFT,2,2,sectionType="topSales")
    writer.addHeader('Salesperson',LEFT,3,3,sectionType="topSales")
    writer.addHeader('Year',LEFT,4,4,sectionType="topSales")
    writer.addHeader('Salesperson',LEFT,5,5,sectionType="topSales")
    writer.addHeader('Year',LEFT,6,6,sectionType="topSales")
    writer.addHeader('Salesperson',LEFT,7,7,sectionType="topSales")


    # ========================================================================
    # Populate report with data
    # ========================================================================
          
    storeInfo = [{'location'   :'Manhattan, KS',
                  'modelLines' : 15,          # Number of bogus models to create
                 },
                 {'location'   :'Memphis, TN',
                  'modelLines' : 65,          # Number of bogus models to create
                 },
                ]
                 
    for store in storeInfo:      
      # ----------------------------------------------------------------------
      # Main section of the store's report 
      # ----------------------------------------------------------------------
      
      # Start the section
      writer.startNewSection("%s Store" % store['location'])
      
      # Fill with data
      for row in self._generateSalesData(store['modelLines']):
        writer.addRow(row)
#         writer.addLine("Test Line", borders=[0,.25,.25,.25])
        
      # We won't compute totals in this sample
      writer.addRow(["Total 1"]+['0']*24, style='Subtotal')
      writer.addRow(["Total 2"]+['0']*24, style='Total')
      
      # ----------------------------------------------------------------------
      # Secondard section
      # ----------------------------------------------------------------------
    
      # Start the new section, suppress the automatic new page at section start
      writer.startNewSection("Top Sales Personel - Last 5 years",sectionType="topSales", newPage=0) 
      
      # Fill with data
      for row in self._generateTopSalespersons(5):
        writer.addRow(row)
        
    writer.close()
    f.close()


  # ==========================================================================
  # Functions to define bogus data for the sample
  # ==========================================================================
  def _generateSalesData(self,lines):
    """
    Simple function to generate random sales data for the sample report.
    
    @param lines: The number of lines of model sales data to generate
    """
    import random
    data = []
    for count in range(lines):
      row = []
      # Build the model number
      letterOffset, number = divmod(count,10)
      model = "%s%s" % (chr(65+letterOffset),number)
      row.append(model)
      
      # Randomly create quarterly sales data for 3 years, set % to 0 for now
      for c in range(12):        
        sales = random.randrange(1,100,1)
        row.append("%s" % sales)
        row.append("0") # not computing %s in the sample
      
      # Add the row to the data being returned  
      data.append(row)  
      
    return data
          
  def _generateTopSalespersons(self,years):
    """
    Simple function to generate random salesperson data for the sample report.
    
    @param years: The number of lines of salesperson data to generate
    """
    import random
    names=['Tom Barker','Linda Carter','Willy Sellut','Peter Smith','Chilly Willy','Betty Bip',
           'Mark Bently','Maynard Thomas','Sally Watson','Tammy Kingston','Shelly White',
           'Rose Parkson','Blair Thomas',
          ]
    
    data = []
    for year in range(2004-years, 2004):
      row1 = []
      row2 = []
      row3 = []
      for q in range(4):
        # Python 2.3 only :(
        #people = random.sample(names,3)
        
        people = {}
        while len(people) < 3:
          people[names[random.randint(1,len(names)-1)]] = ''
        people = people.keys()
        
        row1.append("%s" % year)
        row1.append(people[0])
        row2.append("%s" % year)
        row2.append(people[1])
        row3.append("%s" % year)
        row3.append(people[2])
      data.append(row1)
      data.append(row2)
      data.append(row3)          
    return data
      
# ============================================================================
# Run the sample report
# ============================================================================
if __name__ == '__main__':
  Sample().run()


  
