#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@software: PyCharm
@Version: python3.6
"""
import datetime
import traceback
import time
import logging
import jwt
import simplejson
import simplejson as json
import requests
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.timezone import utc
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from jwt.algorithms import RSAAlgorithm
from ratelimit.decorators import ratelimit

from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN
from Controller.CheckUserData import DataValid, date_handler, RandomStr
from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
    UserAppFrequencyModel, CountryIPModel, CountryModel, RegionModel, P2PIpModel, DeviceDomainModel
from Object.AWS.SesClassObject import SesClassObject
from Object.AliSmsObject import AliSmsObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Service.TemplateService import TemplateService
from django.views.generic import View
import base64
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.shortcuts import HttpResponse
from Ansjer.config import BASE_DIR

#确认设备所在地区
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'
        # number = request.POST.get('number', None)
        # selectRegion = CountryModel.objects.filter(number=number).values('region__api_url')
        # if not selectRegion.exists():
        #     return response.json(0,{"api_url":"https://test.dvema.com"})
        # else:
        #     return response.json(0,{"api_url":selectRegion[0]['region__api_url']})

        # serial_number = request.POST.get('serial_number', None)
        ip = CommonService.get_ip_address(request)
        # ip = '14.102.176.0'
        ipInfo = CommonService.getIpIpInfo(ip, "CN")
        if ipInfo['country_code']:
            device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).values("region__api")
            if device_request_url.exists():
                return response.json(0, {"request_api_url":device_request_url[0]['region__api']})

        # 不存在默认返回美洲地区api。
        api = RegionModel.objects.filter(continent_code='NA').values("api")
        return response.json(0,{"request_api_url": api[0]['api']})


# 根据设备的ip返回域名
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):
        try:
            response = ResponseObject()
            uid = request.GET.get('uid', None)
            serial_number = request.GET.get('serial_number', None)
            if not uid and not serial_number:
                return response.json(444)
            if uid:
                data_dict = {'uid': uid}
                device_domain_qs = DeviceDomainModel.objects.filter(uid=uid)
            else:
                data_dict = {'serial_number': serial_number}
                device_domain_qs = DeviceDomainModel.objects.filter(serial_number=serial_number)
            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']
                device_request_url = CountryModel.objects.filter(country_code=country_code).values('region__api')
                if device_request_url.exists():
                    api = device_request_url[0]['region__api']
                else:   # 默认返回美洲地区api
                    api = RegionModel.objects.filter(continent_code='NA').values('api')[0]['api']
            else:
                # 默认返回美洲地区api
                api = RegionModel.objects.filter(continent_code='NA').values('api')[0]['api']

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


#确认设备所在地区
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, 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'
                        if country == '中国':
                            country = '美国'
                    wf.write(country+'\n')
        return response.json(0)
    except Exception as e:
        print(e)
        return response.json(500, repr(e))
