# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import
import hashlib

from django.conf import settings
from gm_jmessage import common
from gm_jmessage import url

from message import JIM_USER_EXIST

_jim_salt1 = b's\x15\x02~n\x01\x08\x1e\xb4\x94jn\xc4\xc7\t\x88\xa9\x89\xc9O'
_jim_salt2 = b'v[\xfc\xdb\xddH\x86\xbd\xe8\x9d\x19\xaa\xd7 k\xfd\x0f\xb6\r\xf8'


def get_default_es_index_for_write(override=None):
    return override or settings.ES_MSG_WRITE_INDEX


def get_default_es_index_for_read(override=None):
    return override or settings.ES_MSG_READ_INDEX


def get_update_retry_on_conflict(current=None, default=5):
    if current is None:
        return default
    current = int(current)
    if current < 1:
        return 1
    return current


def get_jim_login_info(user_id):
    """
    Define the map of our account system to jim account system.
    """
    juser_id = hashlib.md5(str(user_id) + _jim_salt1).hexdigest()
    jpassword = hashlib.md5(str(user_id) + _jim_salt2).hexdigest()
    return juser_id, jpassword


def is_jim_user(username):
    """Check username whether register in jim server
    reference doc:
        https://docs.jiguang.cn/jmessage/server/rest_api_im/#_3
    """
    uri = '/v1/users/{}'.format(username)
    jmessage = common.JMessage(settings.JIM_APPKEY, settings.JIM_SECRET)
    resp = jmessage._request('GET', None, url.IM_URL + uri)
    content = resp.json()
    return 'username' in content


def register_jim(username, password):
    """Register to jim server
    reference doc:
        https://docs.jiguang.cn/jmessage/server/rest_api_im/#_1
    """
    jmessage = common.JMessage(settings.JIM_APPKEY, settings.JIM_SECRET)
    juser_obj = jmessage.create_users()
    users = [juser_obj.build_user(username, password)]

    resp = juser_obj.regist_user(users)
    body = resp.json()[0]
    # we omit user already exist case.
    if 'error' in body and body['error']['code'] != JIM_USER_EXIST:
        raise Exception(body['error']['message'])
