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

import urllib2
import json
from datetime import datetime

import requests
from django.conf import settings

from gm_types.gaia import (
    CHANNEL_CALLBACK_TYPE,
    CHANNEL_STATUS,
    PLATFORM_CHANNEL,
)
from rpc.tool.log_tool import channel_logger, logging_exception

_VERIFIED = False


def inmobi_active_record(record):
    """InMobi回调"""

    call_back_url = "https://postback.inmobi.cn/track/callback?callback={callback}&et=200&mit={mit}&mid={mid}"

    update_fields = ['active_time', 'update_time']
    time_now = datetime.now()
    record.active_time = time_now
    record.update_time = time_now

    code, msg = 1, CHANNEL_STATUS.ACT_FAIL_GENERAL

    channel_logger.info("InMobi 调用回调函数---")

    if record.callback_type == CHANNEL_CALLBACK_TYPE.GET_CALLBACK:

        click_request = record.click_request
        if not click_request:
            return

        request_params = json.loads(click_request)
        platform_type = record.platform_type
        if platform_type == PLATFORM_CHANNEL.IOS:
            mit = 1
        else:
            if request_params.get("imei_md5"):
                mit = 2
            else:
                mit = 3

        if request_params.get("callback_url"):
            callback_url = urllib2.unquote(request_params.get("callback_url"))
            if '?' in callback_url:
                callback_url = callback_url + '&et=200&mit={mit}&mid={mid}'.format(
                    mit=mit,
                    mid=record.idfa,
                )
            else:
                callback_url = callback_url + '?callback={callback}&et=200&mit={mit}&mid={mid}'.format(
                    callback=request_params.get("callback", ""),
                    mit=mit,
                    mid=record.idfa,
                )
        else:
            callback_url = call_back_url.format(
                callback=request_params.get("callback", ''),
                mit=mit,
                mid=record.idfa,
            )

        try:
            res = requests.get(callback_url)

            if res.status_code == requests.codes.ok:
                code = 0
                msg = CHANNEL_STATUS.ACT_OK
                record.callback_response = res.text or ''
                _response_info_str = record.callback_response
                update_fields.append('callback_response')
            else:
                _response_info_str = ''

            channel_logger.info("InMobo 回调地址:{0}, 回调状态:{1},回调结果:{2}".format(
                callback_url, res.status_code, _response_info_str)
            )
        except:
            logging_exception()
            channel_logger.info("InMobo 回调失败。记录id:{}".format(record.id))
    else:
        channel_logger.info("InMobo 无回调。记录id:{}".format(record.id))

    record.save(update_fields=update_fields)
    return {'error': code, 'msg': msg}
