from __future__ import unicode_literals
from labkey.api_wrapper import APIWrapper

# -------  Example code to download a file from the server -------

# Define the API wrapper that will access the desired container on your server.
# Learn more in the documentation topic here: https://www.labkey.org/Documentation/wiki-page.view?name=pythonDemo#apiWrapper
labkey_server = 'localhost:8080'
container_path = 'Tutorials/File Repository'
context_path = 'labkey'
use_ssl=False
api = APIWrapper(labkey_server, container_path, context_path, use_ssl)

# Helper to build the webdav URL
# :param filePath: The relative file path within the file browser
# :return: the URL to GET the request from
def build_webdav_download_url(filePath):
    sep = '/'
    url = 'http://' + labkey_server

    if context_path is not None:
        url += sep + context_path
    url += sep + '_webdav'

    if container_path is not None:
        url += sep + container_path
    else:
        raise ValueError("container path in server context must be set")

    url += sep + '%40files' + sep + filePath + "?contentDisposition=attachment"
    return url


# Definition of download_file: Download a file from LabKey server
# :param sourceFilepath: The filepath and file name with file extension of the file you
#     want to download from the server (details below)
# :param destinationFilepath: The local filepath to download to (details/examples below)
def download_file(sourceFilepath, destinationFilepath):
    url = build_webdav_download_url(sourceFilepath)

    fileBytes = api.server_context.make_request(url, None, method="GET")['content']
    fileName = sourceFilepath.split('/')[-1]

    f = open(destinationFilepath + fileName, 'wb')
    f.write(fileBytes)
    f.close()


# Source file path is relative to the file root of the 'container_path' set above
#  i.e. this will be everything after @files in the path you can see on your server.
sourceFilepath = "LabKeyDemoFiles/API/ReagentRequestTutorial/Reagents.xls"

# Destination file path (on your local machine) can be relative to where you run the
# script, or absolute. A few examples are below.
destinationFilepath0 = ""                                   # File downloaded to current directory
destinationFilepath1 = "localFolder/"                       # File downloaded to 'localFolder' within current directory
destinationFilepath2 = "/Users/username/Downloads/"   # File downloaded to (my) downloads folder

# Download the file
download_file(sourceFilepath, destinationFilepath0)



