import logging
import time

from django.utils.decorators import method_decorator

from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from Model.models import CountryModel, RegionModel, P2PIpModel, DeviceDomainModel, DeviceDomainRegionModel
from Object.ResponseObject import ResponseObject
from Service.CommonService import CommonService


#确认设备所在地区
class ConfirmRegion(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ConfirmRegion, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        response = ResponseObject()
        request.encoding = 'utf-8'
        try:
            ip = CommonService.get_ip_address(request)
            device_domain_data = {'ip': ip}
            ipInfo = CommonService.getIpIpInfo(ip, 'CN')
            logger = logging.getLogger('info')
            logger.info('设备获取域名---ip:{},country_code:{}'.format(ip, ipInfo['country_code']))
            if ipInfo['country_code']:
                device_domain_data['country_name'] = ipInfo['country_code']
                device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).values("region__api")
                if device_request_url.exists():
                    api = device_request_url[0]['region__api']
                    device_domain_data['api'] = api
                    DeviceDomainModel.objects.create(**device_domain_data)
                    return response.json(0, {'request_api_url': api})

            # 不存在默认返回美洲地区api。
            api = RegionModel.objects.filter(continent_code='NA').values("api")
            device_domain_data['country_name'] = 'NA'
            device_domain_data['api'] = api[0]['api']
            DeviceDomainModel.objects.create(**device_domain_data)
            return response.json(0, {'request_api_url': api[0]['api']})
        except Exception as e:
            print(e)
            return response.json(0, {'request_api_url': 'https://www.dvema.com'})


# 根据设备的ip返回域名和地区id
class ConfirmRegionV2(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ConfirmRegionV2, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        response = ResponseObject()
        serial_number = request.GET.get('serial_number', None)
        if not serial_number:
            return response.json(444)
        try:
            data_dict = {'serial_number': serial_number}
            device_domain_region_qs = DeviceDomainRegionModel.objects.filter(serial_number=serial_number)

            # 根据请求ip确认地区
            request.encoding = 'utf-8'
            ip = CommonService.get_ip_address(request)
            data_dict['ip'] = ip
            ipInfo = CommonService.getIpIpInfo(ip, 'CN')
            country_code = ipInfo['country_code']

            if country_code:
                data_dict['country_name'] = ipInfo['country_name']
                country_qs = CountryModel.objects.filter(country_code=country_code).\
                    values('region__api', 'region__id')
                if country_qs.exists():
                    api = country_qs[0]['region__api']
                    region_id = country_qs[0]['region__id']
                else:   # 默认返回美洲地区api
                    api, region_id = self.get_default_api()
            else:
                # 默认返回美洲地区api
                api, region_id = self.get_default_api()

            # 更新或创建设备域名数据
            data_dict['api'] = api
            data_dict['region_id'] = region_id
            if device_domain_region_qs.exists():
                device_domain_region_qs.update(**data_dict)
            else:
                device_domain_region_qs.create(**data_dict)
            res = {'request_api_url': api, 'region_id': region_id}
            return response.json(0, res)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 获取区域表美洲的相关数据
    @staticmethod
    def get_default_api():
        region_qs = RegionModel.objects.filter(continent_code='NA').values('api', 'id')
        api = region_qs[0]['api']
        region_id = region_qs[0]['id']
        return api, region_id

#确认设备所在地区
class Device_Region(object):

    def get_device_region(self, ip):

        ipInfo = CommonService.getIpIpInfo(ip, "CN")

        #暂时测试国外
        if ipInfo['country_code']:
            device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).values("region__api","region__id")
            if device_request_url.exists():
                return device_request_url[0]['region__id']
        # 不存在默认返回美洲地区api
        api = RegionModel.objects.filter(continent_code='NA').values("id")
        return api[0]['id']


# 根据p2p的ip统计设备所在地区
class StatisticsIpRegion(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(StatisticsIpRegion, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.ipRegion(request.GET)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.ipRegion(request.POST)

    def ipRegion(self, request_dict):
        response = ResponseObject()
        ip = request_dict.get('ip', None)
        uid = request_dict.get('uid', None)
        p2p_request_times = int(request_dict.get('p2p_request_times', 0))
        relay_request_times = int(request_dict.get('relay_request_times', 0))

        if not all([ip, uid]) or (not p2p_request_times and not relay_request_times):
            return response.json(444)

        try:
            now_time = int(time.time())
            p2p_ip_qs = P2PIpModel.objects.filter(uid=uid).values('p2p_request_times', 'relay_request_times')
            if p2p_ip_qs.exists():
                # 已存在数据,更新p2p请求次数和relay请求次数
                p2p_request_times = p2p_ip_qs[0]['p2p_request_times'] + p2p_request_times
                relay_request_times = p2p_ip_qs[0]['relay_request_times'] + relay_request_times
                p2p_ip_qs.update(p2p_request_times=p2p_request_times, relay_request_times=relay_request_times, update_time=now_time)
            else:
                # 根据ip确定位置信息
                ip_info = CommonService.getIpIpInfo(ip, 'CN')
                # 获取大洲,国家,地区,城市
                continent_code = ip_info['continent_code']
                country_name = ip_info['country_name']
                if continent_code == 'AP' and country_name != 'CN':
                    # 如果大洲代码为'AP',国家不为'CN',为亚洲
                    continent_code = 'AS'
                continent_name = RegionModel.objects.filter(continent_code=continent_code).values('name')[0]['name']
                region_name = ip_info['region_name']
                city_name = ip_info['city_name']
                P2PIpModel.objects.create(uid=uid, ip=ip, continent_name=continent_name, country_name=country_name,
                                          region_name=region_name, city_name=city_name, p2p_request_times=p2p_request_times,
                                          relay_request_times=relay_request_times, add_time=now_time, update_time=now_time)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

def confirm_country_with_ip(request):
    '''
    根据ip统计设备所在国家的程序,
    ip.txt放在ASJServer目录下
    '''
    response = ResponseObject()
    try:
        with open('country.txt', 'w', encoding='utf-8') as wf:
            with open('ip.txt', 'r') as rf:
                for ip in rf.readlines():
                    if not ip or ip == '\n':
                        country = 'N/A'
                    else:
                        if '\n' in ip:
                            ip = ip[:-1]
                        ipInfo = CommonService.getIpIpInfo(ip, "CN")
                        country = ipInfo['country_name'] if ipInfo['country_name'] else 'N/A'
                    wf.write(country+'\n')
        return response.json(0)
    except Exception as e:
        print(e)
        return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
