'Import a workflow by reading an url, uploading a file, opening and reading the contents
of a local file, or receiving the textual representation of a workflow via http.'

@web.expose
@web.json
def upload_import_workflow(self, trans, cntrller='workflow', **kwd):

    url = kwd.get('url', '')
    workflow_text = kwd.get('workflow_text', '')
    message = str(escape(kwd.get('message', '')))
    status = kwd.get('status', 'done')
    import_button = kwd.get('import_button', False)
    myexperiment_target_url = ('http://%s/galaxy?galaxy_url=%s' % (trans.app.config.get('myexperiment_url', 'www.myexperiment.org'), url_for('/', qualified=True)))
    workflow_source = kwd.get('workflow_source', 'uploaded    file')
    tool_shed_url = kwd.get('tool_shed_url', '')
    repository_metadata_id = kwd.get('repository_metadata_id', '')
    add_to_menu = util.string_as_bool(kwd.get('add_to_menu', False))
    workflow_name = kwd.get('workflow_name', '')
    if workflow_name:
        workflow_name = encoding_util.tool_shed_decode(workflow_name)
    installed_repository_file = kwd.get('installed_repository_file', '')
    repository_id = kwd.get('repository_id', '')
    if (installed_repository_file and (not import_button)):
        workflow_file = open(installed_repository_file, 'rb')
        workflow_text = workflow_file.read()
        workflow_file.close()
        import_button = True
    if (tool_shed_url and (not import_button)):
        params = dict(repository_metadata_id=repository_metadata_id, workflow_name=encoding_util.tool_shed_encode(workflow_name), open_for_url=True)
        pathspec = ['workflow', 'import_workflow']
        workflow_text = util.url_get(tool_shed_url, password_mgr=self.app.tool_shed_registry.url_auth(tool_shed_url), pathspec=pathspec, params=params)
        import_button = True
    if import_button:
        workflow_data = None
        if url:
            try:
                workflow_data = urllib2.urlopen(url).read()
            except Exception as e:
                message = ('Failed    to    open    URL:    %s.    Exception:    %s' % (escape(url), escape(str(e))))
                status = 'error'
        elif workflow_text:
            workflow_data = workflow_text
        else:
            file_data = kwd.get('file_data', '')
            if (file_data in ('', None)):
                message = 'No    exported    Galaxy    workflow    files    were    selected.'
                status = 'error'
            else:
                uploaded_file = file_data.file
                uploaded_file_name = uploaded_file.name
                if (os.path.getsize(os.path.abspath(uploaded_file_name)) > 0):
                    workflow_data = uploaded_file.read()
                else:
                    message = 'You    attempted    to    upload    an    empty    file.'
                    status = 'error'
        if workflow_data:
            try:
                data = json.loads(workflow_data)
            except Exception as e:
                data = None
                message = 'The    data    content    does    not    appear    to    be    a    Galaxy    workflow.'
                status = 'error'
                log.exception('Error    importing    workflow.')
            if data:
                src = None
                if (cntrller != 'api'):
                    src = workflow_source
                (workflow, missing_tool_tups) = self._workflow_from_dict(trans, data, source=src, add_to_menu=add_to_menu)
                workflow = workflow.latest_workflow
                if workflow_name:
                    workflow.name = workflow_name
                if workflow.has_errors:
                    message += 'Imported,    but    some    steps    in    this    workflow    have    validation    errors.    '
                    status = 'error'
                if workflow.has_cycles:
                    message += 'Imported,    but    this    workflow    contains    cycles.        '
                    status = 'error'
                else:
                    message += ('Workflow    %s    imported    successfully.        ' % escape(workflow.name))
                if missing_tool_tups:
                    if trans.user_is_admin():
                        message += 'The    workflow    requires    the    following    tools    that    are    not    available    in    this    Galaxy    instance.'
                        message += 'You    can    likely    install    the    required    tools    from    one    of    the    Galaxy    tool    sheds    listed    below.<br/>'
                        for missing_tool_tup in missing_tool_tups:
                            (missing_tool_id, missing_tool_name, missing_tool_version, step_id) = missing_tool_tup
                            message += ('Tool    name:    %s,    id:    %s,    version:    %s.' % (escape(missing_tool_name), escape(missing_tool_id), escape(missing_tool_version)))
                        message += '<br/>'
                        for (shed_name, shed_url) in trans.app.tool_shed_registry.tool_sheds.items():
                            if shed_url.endswith('/'):
                                shed_url = shed_url.rstrip('/')
                                url = ('%s/repository/find_tools?galaxy_url=%s' % (shed_url, url_for('/', qualified=True)))
                                if missing_tool_tups:
                                    url += '&tool_id='
                                for missing_tool_tup in missing_tool_tups:
                                    missing_tool_id = missing_tool_tup[0]
                                    url += ('%s,' % escape(missing_tool_id))
                            message += ('url:    %s,    shed    name:    %s.' % (url, shed_name))
                            status = 'error'
                        if (installed_repository_file or tool_shed_url):
                            action = 'center'
                        else:
                            action = 'index'
                        return trans.response.send_redirect(web.url_for(controller='admin', action=action, message=message, status=status))
                    else:
                        pass
                if tool_shed_url:
                    message = ('Workflow    %s    imported    successfully.' % escape(workflow.name))
                    url = ('%s/workflow/view_workflow?repository_metadata_id=%s&workflow_name=%s&message=%s' % (tool_shed_url, repository_metadata_id, encoding_util.tool_shed_encode(workflow_name), message))
                    return trans.response.send_redirect(url)
                elif installed_repository_file:
                    message = ('Workflow    %s    imported    successfully.' % escape(workflow.name))
                    if (cntrller == 'api'):
                        return (status, message)
                    return trans.response.send_redirect(web.url_for(controller='admin_toolshed', action='browse_repository', id=repository_id, message=message, status=status))
                redirect_url = (((url_for('/') + 'workflow?status=') + status) + ('&message=%s' % escape(message)))
                return trans.response.send_redirect(redirect_url)
    if (cntrller == 'api'):
        return (status, message)
    if (status == 'error'):
        redirect_url = (((url_for('/') + 'workflow?status=') + status) + ('&message=%s' % escape(message)))
        return trans.response.send_redirect(redirect_url)
    else:
        return {'url': url, 'message': message, 'status': status, 'myexperiment_target_url': myexperiment_target_url}
