import json
import logging
from oqclib.utils.http_util import send_post_request_with_retries

logger = logging.getLogger(__name__)

class LarkMsg():
    def __init__(self, keys_dict):
        self.keys_dict = keys_dict
        self.request_url = 'https://open.larksuite.com/open-apis/bot/v2/hook/'

    def show_lark(self):
        '''
        show available lark config
        :return: lark keys avaliable in config
        '''
        print(self.keys_dict.keys())

    def send_msg(self, robot, msg): 
        '''
        send lark message
        :param msg: message to send
        :return:
        '''
        key = self.keys_dict[robot]

        mentioned_list = ['@all']

        textJSON = [[{'tag': 'text', 'text': msg}]]

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        textMsg = {
            'msg_type': 'post',
            'content': {'post': {'en_us': {'content': textJSON}}}
        }

        se = json.dumps(textMsg)
        #r = requests.post(self.request_url + key, data=se, headers=headers)
        url = self.request_url + key
        r = send_post_request_with_retries(url, se, 3, headers=headers)
        logger.info("Sending lark resp: {}".format(r.text))


    def send_card(self, robot, card_body: dict):
        '''
        send lark message card
        :param title: lark card title
        :param msg: message to send
        :param robot: lark key name as defined in lark_config
        :return:
        '''
        key = self.keys_dict[robot]
        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }
        textMsg = {
            "msg_type": "interactive",
            "card": card_body
        }
        se = json.dumps(textMsg)
        #r = requests.post(self.request_url + key, data=se, headers=headers)
        url = self.request_url + key
        r = send_post_request_with_retries(url, se, 3, headers=headers)
        logger.info("Sending lark resp: {}".format(r.text))
