#!/usr/bin/env python
import urllib,json,string,sys,configdata
from mysql import mysql
from excel import excel

if __name__ == '__main__':
    strquery=None
    datapush=None
    
    xls=excel()
    db=mysql()
    
    if len(sys.argv)>1:
        kode=sys.argv[1]
        dataexp=db.loadAssoc("SELECT * from tb_expor where id=%s and status=0 ",[kode])
        
        if dataexp.has_key("query"):
            db.query("update tb_expor set status=3 where id=%s",[kode])
            arrjs=json.loads(dataexp['query'])
            
            if arrjs.has_key("query"):
                strquery=arrjs['query']
            
            if arrjs.has_key("datapush"):
                datapush=arrjs['datapush']
        else:
            db.query("update tb_expor set status=2 where id=%s",[kode])
                    
        if(strquery != None and datapush != None):
            datars=db.loadAll(strquery.replace('?','%s'),datapush)
            print strquery.replace('?','%s')
            print datapush
            if(len(datars)>0):
                print "ok"
                arrkolom=arrjs['kolom']
                arrjudul=arrjs['judul']
                arrdatakey=arrjs['datakey']
                print(len(arrjudul), arrjudul)
                print(len(arrdatakey), arrdatakey)
                
                folder=configdata.LSP_CONFIG['FOLDEREXPOR']
                namafile=xls.gentoken(32)
                buatxls=xls.buatfile(arrjudul,arrdatakey,arrkolom,folder,namafile,datars)
                
                if buatxls==True:
                    iduser=dataexp['iduser']
                    filelama=arrjs['namafile']+".xlsx"
                    filebaru=namafile+".xlsx"
                    iddokumen=db.queryid("INSERT INTO tb_dokumen (iduser,tanggal,nama_awal,nama_baru,idjenis,\
                                                                  ukuran,tipefile,folder) \
                        VALUES (%s,now(),%s,%s,%s,%s,%s,%s)",[str(iduser),filelama,filebaru,21,0,'xlsx','exporxls/'])
                    db.query("update tb_expor set status=1,iddokumen=%s where kode=%s",[iddokumen,str(dataexp['kode'])])
                
                
        
        