# Path: slicer_cli_web/docker_resource.py
# class DockerResource(Resource):
#     def __init__(self, name):
#     def getDockerImages(self, params):
#     def deleteImage(self, params):
#     def _deleteImage(self, names, deleteImage):
#     def _deleteDockerImages(self, removed):
#     def parseImageNameList(self, param):
#     def setImages(self, params):
#     def _createPutImageJob(self, nameList, baseFolder):
#     def storeEndpoints(self, imgName, cliName, undoFunction):
#     def deleteImageEndpoints(self, imageList=None):
#     def _generateAllItemEndPoints(self):
#     def addRestEndpoints(self, event):
#     def _dump(self, item, details=False):
#     def getItems(self, folder):
#     def getItem(self, item):
#     def deleteItem(self, item):
#     def getItemXML(self, item):
#     def getMatchingResource(self, name, path, type):
# 
# Path: slicer_cli_web/rest_slicer_cli.py
# def _getParamDefaultVal(param):
# def _canBeBatched(param):
# def _addInputParamToHandler(param, handlerDesc, required=True):
# def _addOutputParamToHandler(param, handlerDesc, required=True):
# def _addReturnParameterFileParamToHandler(handlerDesc):
# def batchCLIJob(cliItem, params, user, cliTitle):
# def batchCLITask(job):  # noqa C901
# def genHandlerToRunDockerCLI(cliItem):  # noqa C901
#     def getBatchParams(params):
#     def cliSubHandler(currentItem, params, user, token):
#     def cliHandler(resource, params):
# def genRESTEndPointsForSlicerCLIsForItem(restResource, cliItem, registerNamedRoute=False):
#         def undoFunction():
# 
# Path: slicer_cli_web/models/docker_image.py
# class CLIItem:
#     def __init__(self, item):
#         self.item = item
#         self._id = item['_id']
#         self.name = item['name']
#         meta = item['meta']
#         self.type = meta['type']
#         self.image = meta.get('image', 'UNKNOWN')
#         self.digest = meta.get('digest', self.image)
#         self.xml = meta['xml']
#         if isinstance(self.xml, str):
#             self.xml = self.xml.encode('utf8')
# 
#         self.restBasePath = self.image.replace(':', '_').replace('/', '_').replace('@', '_')
#         self.restPath = '%s/%s' % (self.restBasePath, self.name)
# 
#     @staticmethod
#     def find(itemId, user):
#         itemModel = Item()
#         item = itemModel.load(itemId, user=user, level=AccessType.READ)
#         if not item:
#             return None
#         return CLIItem(item)
# 
#     @staticmethod
#     def _findAllItemImpl(user=None, extraQuery=None):
#         itemModel = Item()
#         q = {'meta.slicerCLIType': 'task'}
# 
#         if extraQuery:
#             q.update(extraQuery)
# 
#         if user:
#             items = itemModel.findWithPermissions(q, user=user, level=AccessType.READ)
#         else:
#             items = itemModel.find(q)
# 
#         return [CLIItem(item) for item in items]
# 
#     @staticmethod
#     def findAllItems(user=None, baseFolder=None):
#         if not baseFolder:
#             return CLIItem._findAllItemImpl(user)
# 
#         folderModel = Folder()
#         graphLookup = {
#             'from': 'folder',
#             'startWith': '$_id',
#             'connectFromField': '_id',
#             'connectToField': 'parentId',
#             'as': 'children'
#         }
# 
#         if user and not user['admin']:
#             graphLookup['restrictSearchWithMatch'] = folderModel.permissionClauses(user,
#                                                                                    AccessType.READ)
# 
#         # see https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup
#         r = folderModel.collection.aggregate([
#             {
#                 '$match': dict(_id=baseFolder['_id'])
#             },
#             {
#                 '$graphLookup': graphLookup
#             },
#             {
#                 '$project': {
#                     'leaves': '$children._id',
#                 }
#             }
#         ])
# 
#         leaves = next(r)['leaves']
# 
#         return CLIItem._findAllItemImpl(user, {
#             'folderId': {'$in': [baseFolder['_id']] + leaves}
#         })


import functools
import json
import os
import pytest
import time
from pytest_girder.assertions import assertStatusOk, assertStatus
from girder.api import rest
from girder.models.collection import Collection
from girder.models.folder import Folder
from girder.models.item import Item
from slicer_cli_web import docker_resource
from slicer_cli_web import rest_slicer_cli
from slicer_cli_web.models import CLIItem
@pytest.fixture
def handlerFunc(server, admin, folder, file):
    # Make a request to allow there to be some lingering context to handle the
    # testing outside of a request for the actual handler.
    server.request('/system/version')
    rest.setCurrentUser(admin)

    xmlpath = os.path.join(os.path.dirname(__file__), 'data', 'ExampleSpec.xml')

    girderCLIItem = Item().createItem('data', admin, folder)
    Item().setMetadata(girderCLIItem, dict(
        slicerCLIType='task', type='python', image='dockerImage',
        digest='dockerImage@sha256:abc', xml=open(xmlpath, 'rb').read()))

    resource = docker_resource.DockerResource('test')
    item = CLIItem(girderCLIItem)
    handlerFunc = rest_slicer_cli.genHandlerToRunDockerCLI(item)
    yield functools.partial(handlerFunc, resource)


@pytest.mark.plugin('slicer_cli_web')
def test_genHandlerToRunDockerCLI(folder, file, handlerFunc):
    assert handlerFunc is not None

    job = handlerFunc(params={
        'inputImageFile': str(file['_id']),
        'secondImageFile': str(file['_id']),
        'outputStainImageFile_1_folder': str(folder['_id']),
        'outputStainImageFile_1': 'sample1.png',
        'outputStainImageFile_2_folder': str(folder['_id']),

# Path: slicer_cli_web/docker_resource.py
# class DockerResource(Resource):
#     def __init__(self, name):
#     def getDockerImages(self, params):
#     def deleteImage(self, params):
#     def _deleteImage(self, names, deleteImage):
#     def _deleteDockerImages(self, removed):
#     def parseImageNameList(self, param):
#     def setImages(self, params):
#     def _createPutImageJob(self, nameList, baseFolder):
#     def storeEndpoints(self, imgName, cliName, undoFunction):
#     def deleteImageEndpoints(self, imageList=None):
#     def _generateAllItemEndPoints(self):
#     def addRestEndpoints(self, event):
#     def _dump(self, item, details=False):
#     def getItems(self, folder):
#     def getItem(self, item):
#     def deleteItem(self, item):
#     def getItemXML(self, item):
#     def getMatchingResource(self, name, path, type):
# 
# Path: slicer_cli_web/rest_slicer_cli.py
# def _getParamDefaultVal(param):
# def _canBeBatched(param):
# def _addInputParamToHandler(param, handlerDesc, required=True):
# def _addOutputParamToHandler(param, handlerDesc, required=True):
# def _addReturnParameterFileParamToHandler(handlerDesc):
# def batchCLIJob(cliItem, params, user, cliTitle):
# def batchCLITask(job):  # noqa C901
# def genHandlerToRunDockerCLI(cliItem):  # noqa C901
#     def getBatchParams(params):
#     def cliSubHandler(currentItem, params, user, token):
#     def cliHandler(resource, params):
# def genRESTEndPointsForSlicerCLIsForItem(restResource, cliItem, registerNamedRoute=False):
#         def undoFunction():
# 
# Path: slicer_cli_web/models/docker_image.py
# class CLIItem:
#     def __init__(self, item):
#         self.item = item
#         self._id = item['_id']
#         self.name = item['name']
#         meta = item['meta']
#         self.type = meta['type']
#         self.image = meta.get('image', 'UNKNOWN')
#         self.digest = meta.get('digest', self.image)
#         self.xml = meta['xml']
#         if isinstance(self.xml, str):
#             self.xml = self.xml.encode('utf8')
# 
#         self.restBasePath = self.image.replace(':', '_').replace('/', '_').replace('@', '_')
#         self.restPath = '%s/%s' % (self.restBasePath, self.name)
# 
#     @staticmethod
#     def find(itemId, user):
#         itemModel = Item()
#         item = itemModel.load(itemId, user=user, level=AccessType.READ)
#         if not item:
#             return None
#         return CLIItem(item)
# 
#     @staticmethod
#     def _findAllItemImpl(user=None, extraQuery=None):
#         itemModel = Item()
#         q = {'meta.slicerCLIType': 'task'}
# 
#         if extraQuery:
#             q.update(extraQuery)
# 
#         if user:
#             items = itemModel.findWithPermissions(q, user=user, level=AccessType.READ)
#         else:
#             items = itemModel.find(q)
# 
#         return [CLIItem(item) for item in items]
# 
#     @staticmethod
#     def findAllItems(user=None, baseFolder=None):
#         if not baseFolder:
#             return CLIItem._findAllItemImpl(user)
# 
#         folderModel = Folder()
#         graphLookup = {
#             'from': 'folder',
#             'startWith': '$_id',
#             'connectFromField': '_id',
#             'connectToField': 'parentId',
#             'as': 'children'
#         }
# 
#         if user and not user['admin']:
#             graphLookup['restrictSearchWithMatch'] = folderModel.permissionClauses(user,
#                                                                                    AccessType.READ)
# 
#         # see https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup
#         r = folderModel.collection.aggregate([
#             {
#                 '$match': dict(_id=baseFolder['_id'])
#             },
#             {
#                 '$graphLookup': graphLookup
#             },
#             {
#                 '$project': {
#                     'leaves': '$children._id',
#                 }
#             }
#         ])
# 
#         leaves = next(r)['leaves']
# 
#         return CLIItem._findAllItemImpl(user, {
#             'folderId': {'$in': [baseFolder['_id']] + leaves}
#         })


# Path: tests/test_rest_slicer_cli.py
import functools
import json
import os
import pytest
import time
from pytest_girder.assertions import assertStatusOk, assertStatus
from girder.api import rest
from girder.models.collection import Collection
from girder.models.folder import Folder
from girder.models.item import Item
from slicer_cli_web import docker_resource
from slicer_cli_web import rest_slicer_cli
from slicer_cli_web.models import CLIItem

@pytest.fixture
def handlerFunc(server, admin, folder, file):
    # Make a request to allow there to be some lingering context to handle the
    # testing outside of a request for the actual handler.
    server.request('/system/version')
    rest.setCurrentUser(admin)

    xmlpath = os.path.join(os.path.dirname(__file__), 'data', 'ExampleSpec.xml')

    girderCLIItem = Item().createItem('data', admin, folder)
    Item().setMetadata(girderCLIItem, dict(
        slicerCLIType='task', type='python', image='dockerImage',
        digest='dockerImage@sha256:abc', xml=open(xmlpath, 'rb').read()))

    resource = docker_resource.DockerResource('test')
    item = CLIItem(girderCLIItem)
    handlerFunc = rest_slicer_cli.genHandlerToRunDockerCLI(item)
    yield functools.partial(handlerFunc, resource)


@pytest.mark.plugin('slicer_cli_web')
def test_genHandlerToRunDockerCLI(folder, file, handlerFunc):
    assert handlerFunc is not None

    job = handlerFunc(params={
        'inputImageFile': str(file['_id']),
        'secondImageFile': str(file['_id']),
        'outputStainImageFile_1_folder': str(folder['_id']),
        'outputStainImageFile_1': 'sample1.png',
        'outputStainImageFile_2_folder': str(folder['_id']),

        'outputStainImageFile_2_name': 'sample2.png',