<commit_before>import json
from api import *
from api.exception import *
from api.alpineobject import AlpineObject


class User(AlpineObject):
    """
    A collection of functions to deal with user accounts.

    """
    def __init__(self, base_url, session, token):
        super(User, self).__init__(base_url, session, token)

    def create_user(self, username, password, first_name, last_name, email, title="", dept="",
                    notes="Add Via API", admin_role="", app_role="analytics_developer", email_notification=False):
        # TODO: What happens when we have incompatible roles?
        # TODO: How to handle LDAP for password?

        """
        Create a user account with specified parameters.

        :param string username: A unique name.
        :param string password: <PASSWORD>.
        :param string first_name: First Name of the user being created.
        :param string last_name: Last Name of the user being created.
        :param string email: Email of the user being created.
        :param string title: User Title of the user being created.
        :param string dept: Department of the user being created.
        :param string notes: Note for the user being created.
        :param string admin_role: Administration role. One of app_admin, data_admin or an empty string.
        :param string app_role: Application role. One of analytics_developer, data_analyst,
        collaborator or business_user.
        :param bool email_notification: Option to subscribe to email notifications.

        :return: Created user information or error message.
        :rtype: dict
        """

        # Get correct settings for admin and roles for url call:
        admin = False
        roles = ""
        if admin_role == "app_admin":
            admin = True
        elif admin_role == "data_admin":
            roles = "data_admin"

        self.session.headers.update({"Content-Type": "application/json"})  # Set special header for this post
        url = "{0}/users".format(self.base_url)
        url = self._add_token_to_url(url)
        payload = {"username": username,
                   "password": password,
                   "first_name": first_name,
                   "last_name": last_name,
                   "email": email,
                   "title": title,
                   "notes": notes,
                   "dept": dept,
                   "admin": admin,
                   "roles": roles,
                   "user_type": app_role,
                   "subscribed_to_emails": email_notification
                   }
        response = self.session.post(url, data=json.dumps(payload), verify=False)
        self.logger.debug("Adding user, received response code {0} with reason {1}...".format(
            response.status_code, response.reason))
        # self.session.headers.pop("Content-Type")  # Remove header, as it affects other functions
        return response.json()['response']

    def delete_user(self, user_name):
        """
        Delete the user with no error checking.

        :param string user_name: Username of account to be deleted
        :return: Response of the delete action.
        """

        # Deal with statuses: 200 = success, 403 = not admin, 404 = not found

        user_id = self.get_user_id(user_name)
        url = "{0}/users/{1}".format(self.base_url, user_id)
        url = self._add_token_to_url(url)
        self.session.headers.update({"Content-Type": "application/x-www-form-urlencoded"})
        self.logger.debug("Deleting User {0} with id {1}".format(user_name, user_id))
        response = self.session.delete(url)
        self.logger.debug("Received response code {0} with reason {1}".format(response.status_code, response.reason))
        return response

    def delete_user_if_exists(self, user_name):
        """
        Delete the User if the user exists or skip without throwing any error if user doesn't exists

        :param string user_name: Username of the user to be deleted
        :return: Response of the delete action.
        """
        try:
            return self.delete_user(user_name)
        except UserNotFoundException:
            self.logger.debug("User not found, so we don't need to delete the user")

    def update_user(self, user_name, first_name=None, last_name=None, email=None, title=None,
                         dept=None, notes=None, admin_role=None, app_role=None, email_notification=None):
        # TODO: Thouroughly test function!

        """
        Only included fields will be updated.

        :param string user_name: A unique username.
        :param string first_name: New first name of the user.
        :param string last_name: New last name of the user.
        :param string email: New email of the user.
        :param string title: New title of the user.
        :param string dept: New department of the user.
        :param string notes: New notes for the user.
        :param string admin_role: New Administration Role. One of app_admin, data_admin or an empty string
        :param string app_role: New Application Role. One of analytics_developer, data_analyst, \
                                collaborator or business_user.<commit_msg>Removing delete_user_if_exists. We only need one delete user.<commit_after>import json
from api import *
from api.exception import *
from api.alpineobject import AlpineObject


class User(AlpineObject):
    """
    A collection of functions to deal with user accounts.

    """
    def __init__(self, base_url, session, token):
        super(User, self).__init__(base_url, session, token)

    def create_user(self, username, password, first_name, last_name, email, title="", dept="",
                    notes="Add Via API", admin_role="", app_role="analytics_developer", email_notification=False):
        # TODO: How to handle LDAP for password?

        """
        Create a user account with specified parameters.

        :param string username: A unique name.
        :param string password: Password of the user being created.
        :param string first_name: First Name of the user being created.
        :param string last_name: Last Name of the user being created.
        :param string email: Email of the user being created.
        :param string title: User Title of the user being created.
        :param string dept: Department of the user being created.
        :param string notes: Note for the user being created.
        :param string admin_role: Administration role. One of app_admin, data_admin or an empty string.
        :param string app_role: Application role. One of analytics_developer, data_analyst,
        collaborator or business_user.
        :param bool email_notification: Option to subscribe to email notifications.

        :return: Created user information or error message.
        :rtype: dict
        """

        # Get correct settings for admin and roles for url call:
        admin = False
        roles = ""
        if admin_role == "app_admin":
            admin = True
        elif admin_role == "data_admin":
            roles = "data_admin"

        self.session.headers.update({"Content-Type": "application/json"})  # Set special header for this post
        url = "{0}/users".format(self.base_url)
        url = self._add_token_to_url(url)
        payload = {"username": username,
                   "password": password,
                   "first_name": first_name,
                   "last_name": last_name,
                   "email": email,
                   "title": title,
                   "notes": notes,
                   "dept": dept,
                   "admin": admin,
                   "roles": roles,
                   "user_type": app_role,
                   "subscribed_to_emails": email_notification
                   }
        response = self.session.post(url, data=json.dumps(payload), verify=False)
        self.logger.debug("Adding user, received response code {0} with reason {1}...".format(
            response.status_code, response.reason))
        # self.session.headers.pop("Content-Type")  # Remove header, as it affects other functions
        return response.json()['response']

    def delete_user(self, user_name):
        """
        Delete the user with no error checking.

        :param string user_name: Username of account to be deleted
        :return: Response of the delete action.
        """
        # TODO: Deal with statuses? 200 = success, 403 = not admin, 404 = not found

        try:
            user_id = self.get_user_id(user_name)
            url = "{0}/users/{1}".format(self.base_url, user_id)
            url = self._add_token_to_url(url)
            self.session.headers.update({"Content-Type": "application/x-www-form-urlencoded"})
            self.logger.debug("Deleting User {0} with id {1}".format(user_name, user_id))
            response = self.session.delete(url)
            self.logger.debug("Received response code {0} with reason {1}".format(response.status_code, response.reason))
            return response
        except UserNotFoundException:
            self.logger.debug("User not found, so we don't need to delete the user")

    def update_user(self, user_name, first_name=None, last_name=None, email=None, title=None,
                         dept=None, notes=None, admin_role=None, app_role=None, email_notification=None):
        # TODO: Examine errors!

        """
        Only included fields will be updated.

        :param string user_name: A unique username.
        :param string first_name: New first name of the user.
        :param string last_name: New last name of the user.
        :param string email: New email of the user.
        :param string title: New title of the user.
        :param string dept: New department of the user.
        :param string notes: New notes for the user.
        :param string admin_role: New Administration Role. One of app_admin, data_admin or an empty string
        :param string app_role: New Application Role. One of analytics_developer, data_analyst, \
                                collaborator or business_user.
{'fraction_non_alphanumeric': 0.08791534810126582, 'fraction_numerical': 0.003560126582278481, 'mean_word_length': 2.3299308528152785, 'pattern_counts': {'":': 32, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4837867', 'n_tokens_mistral': 2702, 'n_tokens_neox': 2601, 'n_words': 935}