from gettext import gettext as _
import praw
from datetime import datetime
from giara.confManager import ConfManager, SCOPES


def get_authorized_client(retry=False, reddit=None, code=''):
    if reddit is None:
        reddit = get_unauthorized_client()
    confman = ConfManager()
    refresh_token = ''
    if not retry:
        refresh_token = confman.conf['refresh_token']

    if refresh_token != '':
        try:
            return get_preauthorized_client(refresh_token)
        except Exception:
            print(
                _('Error getting client with refresh token, retrying…')
            )
            return get_authorized_client(True)
    try:
        refresh_token = reddit.auth.authorize(code)
        confman.conf['refresh_token'] = refresh_token
        confman.save_conf()
    except Exception:
        if not retry:
            print(
                _('Error authorizing Reddit client, retrying…')
            )
            return get_authorized_client(retry=True)
        else:
            print(
                _('Error authorizing Reddit client after retry, quitting…')
            )
            import sys
            sys.exit(1)
    return reddit


def get_auth_link(reddit):
    return reddit.auth.url(
        SCOPES,
        f'giara-t{datetime.now().timestamp()}',
        'permanent'
    )


USER_AGENT = 'giara by /u/gabmus'
CLIENT_ID = '5rQWiP4kMWi7CA'


def get_unauthorized_client():
    return praw.Reddit(
        client_id=CLIENT_ID,
        client_secret=None,
        redirect_uri='orggabmusgiaradesktop://authcallback',
        user_agent=USER_AGENT
    )


def get_preauthorized_client(refresh_token):
    return praw.Reddit(
        client_id=CLIENT_ID,
        client_secret=None,
        refresh_token=refresh_token,
        user_agent=USER_AGENT
    )
