#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#       export_af3.py
#
#       Copyright 2010 Basmanov Illya <ffsdmad@gmail.com>
#
#       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.

import config
import ffcgi
import libs
from base import bd_sql
from xslt_proc import xml_xsl_proc
import os, sys, inspect, commands, tempfile
sys.stderr = sys.stdout
#from user import user
import utils

def open_zip_file(upload_file, path):
    import re, zipfile
    files = ffcgi.cgi_upload_files( [upload_file], root_dir=path, upload_dir="" )
    if len(files)>0 and files[0][0] is not None:
        zf = zipfile.ZipFile(files[0][1], mode='r')
        for name in zf.namelist():
            if re.search("(DBF|FPT)$",name,re.I):
                newname = os.path.splitext(os.path.basename(name))
                newname = newname[0].upper() + newname[1].lower()
                newname = os.path.join(path, newname)
                try:
                    open(newname,"w").write(zf.read(name))
                except Exception, e:
                    print e, name, newname
                    return False
        return True
    else:
        print "no upload file"
    return False


class export_af3():

    header_print_ok = False
    def make_header(self, attach_name=None, length=None, cntype="text/html; charset=UTF-8"):
        if not self.header_print_ok:
            if attach_name:
                print "Content-Disposition: attachment; filename=%s;"%attach_name
            if length:
                print "Content-Length: %d"%length
            print "Content-Type: %s\n\r"%cntype
            self.header_print_ok = True

    def __init__(self):
        self.make_header(cntype="text/plain; charset=UTF-8")

        pwd = os.getcwd()
        temp_dir = tempfile.mkdtemp()
        os.chmod(temp_dir, 0777)
        #os.chdir(backup_path)
        #libs.print_env()
        if open_zip_file("upload-af3", temp_dir):
            print "Open ZIP file"
            files = ["BIBLIO.dbf", "DELO2.dbf", "DELO3.dbf", "DELO4.dbf", "DELO5.dbf", "DELO.dbf", "DOCUM.dbf", "FOND2.dbf", "FOND3.dbf", "FOND4.dbf", "FOND5.dbf", "FOND6.dbf", "FOND7.dbf", "FOND.dbf", "GEOGRAF1.dbf", "GEOGRAF2.dbf", "GEOGRAF3.dbf", "KOMISSIA.dbf", "MOVE.dbf", "OPIS2.dbf", "OPIS.dbf", "PASPORT.dbf", "PERSONA1.dbf", "PERSONA2.dbf", "PERSONA3.dbf", "RUBRIKA1.dbf", "RUBRIKA2.dbf", "RUBRIKA3.dbf", "SYS.dbf", "TEMATIK1.dbf", "TEMATIK2.dbf", "TEMATIK3.dbf", "VDOCUM.dbf", "VOPROS.dbf", "WORD2.dbf", "WORD3.dbf"]
            #files.append("ARHIV.dbf")
            files.sort()
            files = list([temp_dir+"/"+f for f in files])
            cmd = '%s/plugins/dbf2mysql.pl %s'%(pwd, " ".join(files))
            print cmd
            status, text = commands.getstatusoutput(cmd)
            print status, text
        #os.chdir(pwd)



def main():

    return 0

if __name__ == '__main__': main()
