import click

from staircase.lib.postman_http_client import PostmanClient



class Postman():
    client: PostmanClient

    def __init__(self, client: PostmanClient):
        self.client = client

    def cleanup_postman_collections(self, collection_name, workspaceid):
        response = self.client.request("collections")
        all_collections = response.json()["collections"]
        collections_to_delete = filter(
            lambda collection: collection["name"] == collection_name,
            all_collections,
        )
        for collection in collections_to_delete:
            self.client.request(
                f'collections/{collection["id"]}?workspace={workspaceid}', method="DELETE"
            )

    def get_or_create_workspace(self):
        workspace_name = "StaircaseAPI"

        response = self.client.request(
            f"workspaces",
        )

        def get_id_of_created_workspace(workspaces):
            for workspace in workspaces:
                if workspace["name"] == workspace_name:
                    return workspace["id"]

        workspace_id = get_id_of_created_workspace(response.json()["workspaces"])

        if not workspace_id:
            response = self.client.request(
                f"workspaces",
                method="POST",
                json={
                    "workspace": {
                        "name": workspace_name,
                        "description": "Generated by Staircase CLI",
                        "type": "personal",
                    }
                },
            )
            workspace_id = response.json()["workspace"]["id"]
            click.echo(f"Created new Postman workspace with id: {workspace_id}")
            return workspace_id

        click.echo(
            f"Postman workspace with name {workspace_name} exists with id: {workspace_id}"
        )

        return workspace_id

    def delete_env_by_id(self, env_id: str):
        return self.client.request(f"environments/{env_id}", "DELETE")


class StaircaseNotFoundBundle(Exception):
    ...