try:
    # framework is running
    from .startup_choice import *
except ImportError as _excp:
    # class is imported by itself
    if (
        'attempted relative import with no known parent package' in str(_excp)
        or 'No module named \'omfit_classes\'' in str(_excp)
        or "No module named '__main__.startup_choice'" in str(_excp)
    ):
        from startup_choice import *
    else:
        raise

import requests
import datetime

__all__ = ['_get_omfit_slack_credential', 'get_omfit_slack_token', 'set_omfit_slack_token', 'post_to_slack']


def _get_omfit_slack_credential():
    # user = OMFIT['MainSettings']['SERVER'].get('slack_username', '')
    import getpass

    user = getpass.getuser()  # TODO: Add slack_username to MainSettings and use that to set user instead
    if not len(user):
        raise ValueError('No slack username has been set!')
    return user + '@token.slack.com:0'


def get_omfit_slack_token(token=None):
    """
    Gets slack token
    :param token: string
        token string. if None, read from encrypted credential file.
    :return: string
        Potentially valid slack token
        If it fails, a ValueError is raised
    """
    if not token:
        _, token = decrypt_credential(_get_omfit_slack_credential())
    if len(token) == 76:
        return token
    if not len(token):
        raise ValueError(
            'See https://api.slack.com/custom-integrations/legacy-tokens to create a token, '
            'then use set_omfit_slack_token() to encrypt and store it.'
        )
    raise ValueError('string `%s` is not a valid token' % token)


def set_omfit_slack_token(token):
    """
    Encrypts a slack token and saves it so it can be obtained by get_omfit_slack_token
    :param token: string
        token string to be saved in encrypted form.
    """
    cred = _get_omfit_slack_credential()
    if not len(token):
        return reset_credential(credential=cred)
    if len(token) != 76:
        raise ValueError('string `%s` is not a valid token' % token)
    try:
        encrypt_credential(credential=cred, password='', otp=token)
        printi('slack token stored in:', cred)
    except Exception as e:
        printe('slack token save failed:', repr(e))


def post_to_slack(message='omfit test message', channel='auto_test_reports'):
    """
    Posts slack messages
    :param message: string
        Message body to be posted
    :param channel: string
        Channel identifier, like auto_test_reports
    :return: response instance
        As generated by requests. It should have a `status_code` attribute, which is normally int(200) for successful
        slack posts and probably 4xx for failures.
    """
    url = {'auto_test_reports': 'https://hooks.slack.com/services/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'}
    if channel not in url:
        raise NotImplementedError(
            'To post to the %s channel, request that a new url be added to the appropriate Slack App by Sterling ' 'Smith' % channel
        )
    headers = {'Content-type': 'application/json'}
    params = dict(text=message)
    return requests.post(url[channel], headers=headers, data=json.dumps(params))
