import subprocess
import BuildContext
import logging

class TarballContext(BuildContext.BuildContext):
    contextName="Tarball"
    def __init__(self, args):
        logging = BuildContext.logging
        args.source = os.path.abspath(args.source)
        filename = os.path.basename(args.source)
        if args.name == None:
            args.name = filename.split('.')[0].split('-')[0]
        BuildContext.BuildContext.__init__(self, args)
        
        if not os.path.exists(args.build):
            os.mkdir(args.build)
        os.chdir(args.build)
        ret = subprocess.call(["tar","xf",args.source])
        files = os.listdir(args.build)
        if len(files) == 1:
            args.build+=os.path.sep+files[0]
        args.source = args.build
        logging.info("Building in "+args.build)

    @staticmethod
    def canHandle(args):
        filename = os.path.basename(args.source)
        return os.path.isfile(args.source) and ("tar" in filename.split('.'))
        
BuildContext.register(TarballContext)
class DirectoryContext(BuildContext.BuildContext):
    contextName="Directory"
    def __init__(self, args):
        args.source = os.path.abspath(args.source)
        if args.name == None:
            args.name = os.path.basename(args.source)
        BuildContext.BuildContext.__init__(self,args)
    
    def save(self):
        f = open(self.args().source+os.path.sep+".buildrc","w")
        cPickle.dump(self.args(),f)
        f.close()
    
    def load(self):
        if os.path.exists(self.args().source+os.path.sep+".buildrc"):
            f = open(self.args().source+os.path.sep+".buildrc","r")
            self.setArgs(cPickle.load(f))
            f.close()
    
    @staticmethod
    def parseArgs(options):
        options.add_option("-n", "--no-external-build", action="store_false", dest="external", help="Don't build outside of the source")
        return options
    
    @staticmethod
    def canHandle(args):
        BuildContext.BuildContext.logging.debug("Checking if %s is a directory",args.source)
        return os.path.isdir(args.source)

BuildContext.register(DirectoryContext)