import sys,json,configdata,io,cStringIO,ftplib
from PIL import Image
from mysql import mysql
from pathlib import Path
from ftplib import FTP 

if __name__ == '__main__':
    if len(sys.argv)>1:
        lebarbaru=400
        datatipe=["jpg","jpeg","png","bmp"];
        
        db=mysql()
        iddokumen=sys.argv[1]
        datadok=db.loadAssoc("SELECT * from tb_dokumen where id=%s ",[str(iddokumen)])
        db.closedb()
        
        if "id" not in datadok:
            print("Data dokumen tidak di temukan")
            sys.exit()
        
        strtipefile=datadok['tipefile'];
        if strtipefile.lower() not in datatipe:
            print("Data dokumen tidak di dukung")
            sys.exit()
            
        image = Image.open(configdata.PY_CONFIG['HOMEDIR']+configdata.PY_CONFIG['HTMLDIR']+datadok['folder']+datadok['nama_baru'])
        lebargambar, tinggigambar= image.size
        
        imagebaru=image
        if lebargambar>lebarbaru:
            persen=float(lebarbaru)/float(lebargambar)
            tinggibaru=float(tinggigambar)*persen
            imagebaru=image.resize((int(lebarbaru), int(tinggibaru)))
        
        b = io.BytesIO()
        imagebaru.save(b, image.format)
        b.seek(0)
        
        try: 
            print("konek ftp..." )
            ftp = FTP("localhost")
            ftp.login(configdata.PY_CONFIG['USERFTP'], configdata.PY_CONFIG['PASSWORDFTP']) 
            lokasithumb=configdata.PY_CONFIG['HOMEDIR']+configdata.PY_CONFIG['FTPDIR']+datadok['folder']+'thumb'
            dircek=Path(lokasithumb)
            
            lokasidir=configdata.PY_CONFIG['FTPDIR']+datadok['folder']+'thumb'
            if dircek.is_dir() is False:
                print("mkd")
                ftp.mkd(lokasidir)
               
            file = cStringIO.StringIO(b.read()) 
            
            ftp.cwd(lokasidir)
            ftp.storbinary('STOR ' + datadok['nama_baru'], file) 
            ftp.sendcmd('SITE CHMOD 640 ' + datadok['nama_baru'])

            ftp.quit() 
            file.close() 
            
            db=mysql()
            dataup={
                "thumb":1
            }
            
            db.update("tb_dokumen", dataup, ["id"], [iddokumen])
            db.closedb()
            print("Simpan gambar thumb berhasil .... " )
        except Exception as e:
            print ("Gagal ubah gambar error %s" % e)
            db=mysql()
            dataup={
                "pesan":"Gagal ubah gambar error "+e
            }
            
            db.update("tb_dokumen", dataup, ["id"], [iddokumen])
            sys.exit()
