# Time-stamp: <2001-07-16 15:53:10 Administrator>

# Code and design by Casey Crabb (crabbkw@rose-hulman.edu)
# This code is licensed under the BSD license.
# See the LICENSE file for details
#
# Copyright Casey Crabb (crabbkw@rose-hulman.edu) July 2001
#

import urllib
import BaseHTTPServer
import SimpleHTTPServer
import os
import string
import sys
from threading import *
def callback(blocksxfered, blocksize, totalsize):
    print blocksxfered * blocksize,"of", totalsize

class IMComHTTPServer(Thread):
    def __init__(self, path, port):
        Thread.__init__(self)
        if(path == ""):
            self.path = '.'
        else:
            self.path = path
        self.port = port
        #self.callback = callback
        self.done = 0

    def go(self):
        handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        os.chdir(self.path)
        server_address = ('', self.port)
        httpd = BaseHTTPServer.HTTPServer(server_address, handler)
        httpd.handle_request()

    def run(self):
        self.go()
        self.done = 1
        # self.callback.handleTransferComplete()

class FileGet(Thread):
    def __init__(self, jid, url, id, listener):
        Thread.__init__(self)
        self.jid = jid
        self.url = url
        self.id = id
        self.listener = listener

    def run(self):
        try:
            os.mkdir(os.environ['HOME']+"/.imcom/files",0700)
        except:
            pass
        try:
            path = os.environ['HOME']+"/.imcom/files" + \
                   self.url[string.rfind(self.url,"/"):]
            urllib.urlretrieve(self.url, path)
            self.listener.handleFileReceived(self.jid,self.url,self.id)
        except:
            self.listener.handleFileErrorReceived(self.jid,self.url,self.id,
                                                  sys.exc_info()[0],
                                                  sys.exc_info()[1])



if __name__ == "__main__":
    s = IMComHTTPServer("/tmp",8000)
    s.start()
    #urllib.urlretrieve("http://137.112.201.243/games/divx_311alpha.exe",
    #                   "/tmp/test",callback)
