from phaser.pipeline.proxy import common

class QueryParams(object):
    """
    Parameters for performing a query
    """
    
    def __init__(self, database, format):
        
        self.database = database
        self.format = format
        
        
    @classmethod
    def PDB(cls, format):
        
        if format not in [ "pdb", "pdbml", "mmcif", "fasta" ]:
            raise ValueError, "Unknown format '%s' for PDB data"
        
        return cls( database = "pdb", format = format )


NAME = "EBI DbFetch service"


def check():
    
    if not common.is_online( url = "http://www.ebi.ac.uk/cgi-bin/dbfetch" ):
        raise RuntimeError, "Cannot contact %s" % str( self )


def fetch_single(identifier, params):

    return fetch_multiple( identifiers = [ identifier ], params = params )


def fetch_multiple(identifiers, params):

    result = common.Download(
        url = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch",
        data = {
            "db": params.database,
            "id": ",".join( set( identifiers ) ),
            "format": params.format,
            "style": "raw",
            }
        )
    
    if result.data.startswith( "ERROR" ):
        result.data = ""
    
    return result
