#=============================================================================
#
#  Copyright (c) Kitware, Inc.
#  All rights reserved.
#  See LICENSE.txt for details.
#
#  This software is distributed WITHOUT ANY WARRANTY; without even
#  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.  See the above copyright notice for more information.
#
#=============================================================================
"""
Python operation for testing access to NERSC and Girder/Cumulus systems.
"""

import os
import sys

# Workaround for missing site-packages path in developer builds
# site_path = None
# if sys.platform == 'win32':
#   site_path = os.path.join(sys.prefix, 'bin', 'Lib', 'site-packages')
# elif sys.platform == 'darwin':
#   site_path = os.path.join(sys.prefix, os.pardir, os.pardir, os.pardir, os.pardir, 'Python')
# elif sys.platform == 'linux':
#   site_path = os.path.join(sys.prefix, 'lib', 'python3.8', 'site-packages')
# else:
#   print(f'Unrecognized platform {sys.platform}')
# if site_path is not None:
#   abs_path = os.path.abspath(site_path)
#   if os.path.exists(abs_path) and abs_path not in sys.path:
#       print(f'Adding to sys.path: {abs_path}')
#       sys.path.append(abs_path)

import smtk
import smtk.attribute
import smtk.io
import smtk.operation

template = """
<SMTK_AttributeResource Version="4">
  <Definitions>
    <AttDef Type="test-spec" BaseType="operation" Label="Spec" />
    <AttDef Type="test-result" BaseType="result" />
  </Definitions>
</SMTK_AttributeResource>
"""

class ExportConnectTest(smtk.operation.Operation):
    def createSpecification(self):
        spec = self.createBaseSpecification()

        reader = smtk.io.AttributeReader()
        err = reader.readContents(spec, template, self.log())
        if err:
            print('Error creating specification')
        return spec

    def operateInternal(self):
        smtk.io.Logger.addDebug(self.log(), 'Testing logger')
        print('import girder_client')
        try:
            import girder_client
            import requests
        except ImportError:
            msg = 'FAILED to import girder_client'
            smtk.io.Logger.addError(self.log(), msg)
            print(msg)

            # Also dump path
            print('sys.path:')

            for p in sys.path:
                print(p)
            return self.createResult(smtk.operation.Operation.Outcome.FAILED)

        girder_url = 'https://ace3p.kitware.com'
        nersc_url = 'https://newt.nersc.gov/newt'

        print('Making NEWT request')
        url = '{}/status/cori'.format(nersc_url)
        try:
            r = requests.get(url)
            r.raise_for_status()
            print(r.text)
        except Exception as ex:
            smtk.io.Logger.addWarning(self.log(), str(ex))
            print(ex)
            msg = 'FAILED to connect to NERSC (NEWT api)'
            smtk.io.Logger.addError(self.log(), msg)
            print(msg)
            return self.createResult(smtk.operation.Operation.Outcome.FAILED)

        print('Making Girder request')
        url = '{}/api/v1/system/check?mode=basic'.format(girder_url)
        try:
            r = requests.get(url)
            r.raise_for_status()
        except Exception as ex:
            print('FAILED to connect to GIRDER/CLIENT')
            print(ex)
            return self.createResult(smtk.operation.Operation.Outcome.FAILED)
        print(r.text)

        # We made it
        print('All tests PASS')
        return self.createResult(smtk.operation.Operation.Outcome.SUCCEEDED)
