#!/usr/local/bin/maxx-python
# usage exportNeaAllRelaventIndividuals.py pathToRoot conffile
#
# Attempt to export from CL with new exporter all individuals
# relavent to a copany.  This is all primary, billing, directory contacts
# and all individuals otherwise related to Company via CompanyRole

import sys
if len(sys.argv)<2:
    print "first arg needs to be pathToRoot"
    sys.exit(-1)
else:
    pathToRoot = sys.argv[1]
sys.path.append(pathToRoot+"/libs")    # first arg is path to root
sys.path.append(pathToRoot)
from framework.CLExport import CLExport

import PLayer.PersistentCriteria
PCAttr = PLayer.PersistentCriteria.PCAttribute
PC  = PLayer.PersistentCriteria.PersistentCriteria
EQ  = PC.EQUALS
OR  = PC.OR
IN  = PC.IN
AND = PC.AND

class exportNpraAllRelevantIndividuals(CLExport):

    def getPC(cls):
        """all active Individuals related to a company as a contact
        """
        Individual = cls.h.getPOClass('Individual')
        pc = PC(PCAttr(Individual, 'personalStatus'),
                IN,
                (1,)) # active
##         sql = """select distinct hex(i.individualid) id from Individual i
##                        left join Company ck on
##                            i.individualid = ck.keycontactid
##                        left join Company2AlternateContact ak on
##                            ak.individualid=i.individualid
##                        left join Company bk on
##                            bk.billingcontactid=i.individualid
##                        left join Company dk on
##                            dk.directorycontactid=i.individualid
##                        left join CompanyRole cr on
##                            cr.individualid=i.individualid
##                    where ck.companyid is not null
##                       or ak.companyid is not null
##                       or bk.companyid is not null
##                       or dk.companyid is not null
##                       or cr.branchid is not null"""
##         rs = cls.pb.processSql(sql)
        
        #idlist = [ '0x'+row['id'] for row in rs ]
        #print idlist

        idlist = cls.pb.processCriteria(Individual, pc, idList=1)

        pc = PC(pc, AND,
                PC(PCAttr(Individual, 'id'),
                   IN,
                   idlist))
        return pc
    getPC = classmethod(getPC)

    def getClass(cls, def_=None):
        return cls.h.getPOClass('Individual')
    getClass = classmethod(getClass)

    def getExporter(cls):
        exporter = cls.h.getExporterClass('ContactsExporter')\
                   (cls.pb, cls.h)
        exporter.getPOClass = cls.getClass
        return exporter
    getExporter = classmethod(getExporter)

if __name__ == '__main__':
    profile = 0
    if profile:
        import profile
        profile.run("exportNpraAllRelevantIndividuals.run()")
    else:
        exportNpraAllRelevantIndividuals.run()