import os
import socket
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token='xoxb-210953113479-4038889044023-eVoy6Cy5U5PQB6GmMOKDIxa4')

def detect_pause(s):
    hostname = socket.gethostname()
    msg = '{} has been paused: {}'.format(hostname, s)
    try:
        response = client.chat_postMessage(channel='#ebm_git', text=msg)
    except SlackApiError as e:
        # You will get a SlackApiError if "ok" is False
        assert e.response["ok"] is False
        assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")



def report_to_slack(args, acc=-1., racc=-1.):
    hostname = socket.gethostname()
    msg = '{}: {} has been fininshed. acc: {}, racc: {}'.format(hostname, \
                                                        args.exp, acc, racc)
    try:
        response = client.chat_postMessage(channel='#ebm_git', text=msg)
    except SlackApiError as e:
        # You will get a SlackApiError if "ok" is False
        assert e.response["ok"] is False
        assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")


def upload_plots_to_slack(args, path_lst, str_lst=None):
    hostname = socket.gethostname()
    msg = '{}: {}({}) result plots.'.format(hostname, args.exp)
    try:
        response = client.chat_postMessage(channel='#ebm_git', text=msg)
    except SlackApiError as e:
        # You will get a SlackApiError if "ok" is False
        assert e.response["ok"] is False
        assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")
    try:
        filepath="./tmp.txt"
        response = client.files_upload(channels='#ebm_git', file=filepath)
        assert response["file"]  # the uploaded file
    except SlackApiError as e:
        # You will get a SlackApiError if "ok" is False
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")

    # slack.chat.post_message('#ebm_git', msg, as_user=False)
    # for path in path_lst:
        # slack.files.upload(path, channels='#ebm_git')
    # if str_lst is not None:
        # for result_str in str_lst:
            # slack.chat.post_message('#ebm_git', result_str, as_user=True)


if __name__ == '__main__':
    import sys
    sys.path.insert(0, os.getcwd())
    # since slacker.py is located at tool
    from args import get_general_args
    args = get_general_args()
    report_to_slack(args)
