#!/usr/bin/env python
# -*- coding: utf-8 -*-

###############################################################################
#  Copyright Kitware Inc.
#
#  Licensed under the Apache License, Version 2.0 ( the "License" );
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
###############################################################################

import girder_client
import json
import mock
import os
import shutil
import six
import time

from girder import config, events
from tests import base

os.environ['GIRDER_PORT'] = os.environ.get('GIRDER_TEST_PORT', '20200')
config.loadConfig()  # Must reload config to pickup correct port


def setUpModule():
    plugins = os.environ.get('ENABLED_PLUGINS', '')
    if plugins:
        base.enabledPlugins.extend(plugins.split())
    base.startServer(False)


def tearDownModule():
    base.stopServer()


class PythonClientTestCase(base.TestCase):

    def setUp(self):
        base.TestCase.setUp(self)

        def writeFile(dirName):
            filename = os.path.join(dirName, 'f')
            f = open(filename, 'w')
            f.write(filename)
            f.close()

        # make some temp dirs and files
        self.libTestDir = os.path.join(os.path.dirname(__file__),
                                       '_libTestDir')
        # unlink old temp dirs and files first
        shutil.rmtree(self.libTestDir, ignore_errors=True)

        os.mkdir(self.libTestDir)
        writeFile(self.libTestDir)
        for subDir in range(0, 3):
            subDirName = os.path.join(self.libTestDir, 'sub'+str(subDir))
            os.mkdir(subDirName)
            writeFile(subDirName)

    def tearDown(self):
        shutil.rmtree(self.libTestDir, ignore_errors=True)

        base.TestCase.tearDown(self)

    def testRestCore(self):
        client = girder_client.GirderClient(port=os.environ['GIRDER_PORT'])

        # Register a user
        user = client.createResource('user', params={
            'firstName': 'First',
            'lastName': 'Last',
            'login': 'mylogin',
            'password': 'password',
            'email': 'email@email.com'
        })

        self.assertTrue(user['admin'])

        # Test authentication with bad args
        flag = False
        try:
            client.authenticate()
        except Exception:
            flag = True

        self.assertTrue(flag)

        # Test authentication failure
        flag = False
        try:
            client.authenticate(username=user['login'], password='wrong')
        except girder_client.AuthenticationError:
            flag = True

        self.assertTrue(flag)