import requests
import features.src.support.helpers as helpers
import os


class ResetEnvironment:
    def getSpaces(self):
        serverAddress = os.getenv("WIT_API")
        osioUsername = os.getenv("OSIO_USERNAME")
        headers = {'Accept': 'application/json',
                   'X-App': 'OSIO',
                   'X-Git-Provider': 'GitHub',
                   'Content-Type': 'application/json'}
        r = requests.get(
            '{}/api/namedspaces/{}'.format(serverAddress, osioUsername),
            headers=headers
        )
        spaceIDs = []
        try:
            respJson = r.json()
            spaces = respJson["data"]
            for space in spaces:
                spaceIDs.append(space["id"])
            return spaceIDs
        except ValueError:
            return None

    def removeSpaces(self):

        # Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)"
        theToken = helpers.get_user_tokens().split(";")[0]
        print('Starting removing spaces.....')

        spacesIDs = self.getSpaces()
        print('Number of spaces before removing: {}'.format(len(spacesIDs)))

        serverAddress = os.getenv("WIT_API")

        authHeader = 'Bearer {}'.format(theToken)

        headers = {'Accept': 'application/json',
                   'Authorization': authHeader,
                   'X-App': 'OSIO',
                   'X-Git-Provider': 'GitHub',
                   'Content-Type': 'application/json'}

        # delete spaces
        for spaceID in spacesIDs:
            print('Deleting space {}'.format(spaceID))
            r = requests.delete(
                '{}/api/spaces/{}'.format(serverAddress, spaceID),
                headers=headers
            )
            assert r.status_code == 200

            if r.status_code != 200:
                print(
                    "ERROR - Request to delete space {} failed - error code = {}"
                    .format(spaceID, r.status_code)
                )

        print('Number of spaces after removing: {}'.format(len(self.getSpaces())))
        print('Spaces removed!')

    def cleanTenant(self):
        # Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)"
        theToken = helpers.get_user_tokens().split(";")[0]

        print('Starting cleaning tenant.....')

        serverAddress = os.getenv("WIT_API")
        authHeader = 'Bearer {}'.format(theToken)

        headers = {'Accept': 'application/json',
                   'Authorization': authHeader,
                   'X-App': 'OSIO',
                   'X-Git-Provider': 'GitHub',
                   'Content-Type': 'application/json'}
        r = requests.delete(
            '{}/api/user/services'.format(serverAddress),
            headers=headers
        )
        assert r.status_code == 200
        r = requests.patch(
            '{}/api/user/services'.format(serverAddress),
            headers=headers
        )
        assert r.status_code == 200
        print('Tenant is cleaned.....')

@@ -67,16 +67,45 @@
 ort os%0A%0A
+from pyshould import should%0A%0A
 %0Aclass R
@@ -1210,16 +1210,58 @@
 IT_API%22)
+%0A        cheAddress = os.getenv(%22CHE_API%22)
 %0A%0A      
@@ -1599,16 +1599,1706 @@
 cesIDs:%0A
+            print('Looking for codebases of space: %7B%7D'.format(spaceID))%0A            r = requests.get(%0A                '%7B%7D/api/spaces/%7B%7D/codebases'.format(serverAddress, spaceID),%0A                headers=headers%0A            )%0A            r.status_code %7C should.be(200).desc(%22Status code for response to get space codebases is 200.%22)%0A            codebases = r.json()%5B%22data%22%5D%0A            if codebases is not None:%0A                for cb in codebases:%0A                    cbID = cb%5B%22id%22%5D%0A                    print('Looking for workspaces of codebase: %7B%7D'.format(cbID))%0A                    r = requests.get(%0A                        '%7B%7D/api/codebases/%7B%7D/workspaces'.format(serverAddress, cbID),%0A                        headers=headers%0A                    )%0A                    r.status_code %7C should.be(200).desc(%22Status code for response to get codebase workspaces is 200.%22)%0A                    workspaces = r.json()%5B%22data%22%5D%0A                    if workspaces is not None:%0A                        for ws in workspaces:%0A                            wsID = ws%5B%22attributes%22%5D%5B%22id%22%5D%0A                            wsName = ws%5B%22attributes%22%5D%5B%22name%22%5D%0A                            print('Deleting workspace: %7B%7D (%7B%7D)'.format(wsID, wsName))%0A                            r = requests.delete(%0A                                '%7B%7D/api/workspace/%7B%7D'.format(cheAddress, wsID),%0A                                headers=headers%0A                            )%0A                            r.status_code %7C should.be(204).desc(%22Status code for response to delete workspace is 204.%22)%0A                    else:%0A                        print(%22No workspaces found.%22)%0A            else:%0A                print(%22No codebases found.%22)%0A%0A
         
@@ -3506,35 +3506,95 @@
     
-assert r.s
+r.status_code %7C should.be(200).desc(%22S
 tatus
-_
+ 
 code 
-==
+for response to delete space is
  200
+.%22)
 %0A%0A  

Delete che workspaces for spaces during env reset.