# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
import pymongo
import datetime
import re,math,os
import MySQLdb

zone_want=MySQLdb.connect(db='jx_security',host='rds7m888213p5s6g4xgoo.mysql.rds.aliyuncs.com',user='huangwenbo',passwd='hwb_123_JX',port =3306,charset = 'utf8')
cur = zone_want.cursor()


con=pymongo.MongoClient('121.40.216.11',8081)  # test  139.196.201.208
db=con.monitordb

def my_sql():
    
    cur.execute("""SELECT y.address,count(1) AS c 
FROM jx_security.c_account_shop AS ass, jx_security.s_shop AS s, jx_security.y_info_account AS y
WHERE s.isDelete = 0 AND s.isUsing = 1 AND s.shopId = ass.shopId AND ass.isDelete = 0 AND y.accountId = ass.accountId AND y.isDelete = 0 AND y.regionId IS NOT NULL AND y.regionId > 0
GROUP BY y.address""")
    zone={}
    zone_dict=[]
    pre=None
    sum=0
    patt = re.compile(ur'[\u4E00-\u9FA5]{3}')
    for data in cur.fetchall():
        if pre!=patt.findall(data[0])[0:1] and sum==0:
            pre= patt.findall(data[0])[0:1]
            sum+=data[1]
        elif pre==patt.findall(data[0])[0:1] and sum!=0:
            sum+=data[1]
        elif pre!=patt.findall(data[0])[0:1] and sum!=0:
            zone[''.join(pre)]=sum
            sum=0
            
        else:
            print "error"
        
    zone_list=sorted(zone.iteritems(),key=lambda d:d[1],reverse=True)
    return zone_list
# Create your views here.
def hour_n(delta_h):
    all_dict={}
    x_list=[]  
    y0_list=[]                 # x data
    y1_list=[]              # very minutes count 
    y2_list=[]                # mes count
    pattern=re.compile('\d{2}:\d{2}')
    eight_bug=datetime.timedelta(hours=8)
    
    now=datetime.datetime.now()
    now=now-eight_bug
    
    delta=datetime.timedelta(hours=delta_h)
    before_hour_n=now-delta                   # n hour before
    
    for i in  db.msgCount.aggregate([{'$match':{'countTime':{'$gt':before_hour_n,'$lte':now}}}]):  #.sort('countTime',-1).limit(60):    #  mongodb  data
      
        if i['countTime']<=now:              #and i['countTime']>=before_hour_n
            
            xtime=i['countTime']+eight_bug
            s=str(xtime)
            s_val=pattern.search(s).group()
            x_list.append(s_val)
            y1_list.append(i['count'])
            y0_list.append(i['count']*20)
    for i in db.httpReqCount.aggregate([{'$match':{'countTime':{'$gt':before_hour_n,'$lte':now}}}]):
        if i['countTime']<=now:
 
            y2_list.append(i['count']) 
                
    all_dict={"x_list":x_list,"y1_list":y1_list,"y2_list":y2_list,"y0_list":y0_list}
        
    json_data=json.dumps(all_dict)   
        
    return json_data
def right_analysis(data1,data2):
    
    datalist=[]
    datalist1=[]
    json_dict={}  
    
    data_every_day1=[]  # after use it for                     message 
    every_day_tmp1=[]                 
    
    redata1=re.match("(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})",data1)
    redata2=re.match("(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})",data2)
    
    del_time=datetime.timedelta(hours=8)            # must do it
    
    data1_year,data1_month,data1_day,data1_hour,data1_minute=int(redata1.group(1)),int(redata1.group(2)),int(redata1.group(3)),int(redata1.group(4)),int(redata1.group(5))
    data2_year,data2_month,data2_day,data2_hour,data2_minute=int(redata2.group(1)),int(redata2.group(2)),int(redata2.group(3)),int(redata2.group(4)),int(redata2.group(5))
    
    
    all_data1=datetime.datetime(year=data1_year, month=data1_month, day=data1_day, hour=data1_hour, minute=data1_minute, second=0, microsecond=0, tzinfo=None)
    all_data1=all_data1-del_time
    all_data2=datetime.datetime(year=data2_year, month=data2_month, day=data2_day, hour=data2_hour, minute=data2_minute, second=0, microsecond=0, tzinfo=None)
    all_data2=all_data2-del_time
    
    
    dataset=db.msgCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}}])
    
    
    
    sum_it_list=db.msgCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$sum': '$count' } } }])
    max_it_list=db.msgCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$max': '$count' } } }])
    avg_it_list=db.msgCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$avg': '$count' } } }])
    min_it_list=db.msgCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$min': '$count' } } }])
    
    for i in sum_it_list:
        sum_it=i['count']
    for i in max_it_list:
        max_it=i['count']
    for i in avg_it_list:
        avg_it=round(i['count'],2)
    for i in min_it_list:
        min_it=i['count']
   
    max_avg_it=round((max_it+avg_it)/2,2)                    # for pie chart 
    min_avg_it=round((min_it+avg_it)/2,2)
   
    
    pie_1=db.msgCount.find({'count':{'$gte':min_it,'$lte':min_avg_it}}).count()       #   4 items for pie 
    pie_2=db.msgCount.find({'count':{'$gte':min_avg_it,'$lte':avg_it}}).count()
    pie_3=db.msgCount.find({'count':{'$gte':avg_it,'$lte':max_avg_it}}).count()
    pie_4=db.msgCount.find({'count':{'$gte':max_avg_it,'$lte':max_it}}).count()
    
    
    dataset1=db.httpReqCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}}])
    
    sum_msg_list=db.httpReqCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$sum': '$count' } } }])
    max_msg_list=db.httpReqCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$max': '$count' } } }])
    avg_msg_list=db.httpReqCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$avg': '$count' } } }])
    min_msg_list=db.httpReqCount.aggregate([{'$match':{'countTime':{'$gte':all_data1,'$lte':all_data2}}},{ '$group': { '_id':'_class', 'count': { '$min': '$count' } } }])
    
    for i in sum_msg_list:
        sum_msg=i['count']
    for i in max_msg_list:
        max_msg=i['count']
    for i in avg_msg_list:
        avg_msg=round(i['count'],2)
    for i in min_msg_list:
        min_msg=i['count']
        
    max_avg_msg=round((max_msg+avg_msg)/2,2)               # for pie chart 
    min_avg_msg=round((min_msg+avg_msg)/2,2)
    
    pie_msg_1=db.httpReqCount.find({'count':{'$gte':min_msg,'$lte':min_avg_msg}}).count()
    pie_msg_2=db.httpReqCount.find({'count':{'$gte':min_avg_msg,'$lte':avg_msg}}).count()
    pie_msg_3=db.httpReqCount.find({'count':{'$gte':avg_msg,'$lte':max_avg_msg}}).count()
    pie_msg_4=db.httpReqCount.find({'count':{'$gte':max_avg_msg,'$lte':max_msg}}).count()
    
    
    zone=[]
    count=[]
    sum_count=0
    zone_list=my_sql()
    print "----------------------",zone_list
    for i in zone_list:
        if i[1]>30:
            zone.append(i[0])
            count.append(i[1])
        else:
            sum_count+=i[1]
    zone.append("other")                  # other select 
    count.append(sum_count)                 # the sum of other count  
            
    print "----------------------",zone
    print "----------------------",count
    json_dict={"sum_it":sum_it,"max_it":max_it,"avg_it":avg_it,"min_it":min_it,"sum_msg":sum_msg,"max_msg":max_msg,"avg_msg":avg_msg,"min_msg":min_msg,\
               "pie_1":pie_1,"pie_2":pie_2,"pie_3":pie_3,"pie_4":pie_4,"pie_msg_1":pie_msg_1,"pie_msg_2":pie_msg_2,"pie_msg_3":pie_msg_3,"pie_msg_4":pie_msg_4,\
               'province':zone,'province_count':count}
    
    json_data=json.dumps(json_dict)
    return json_data

def dispersion(avg,datalist):
    avg_list=[]
    for i in datalist:
        avg_list.append((i-avg)**2)
    result=round(math.sqrt(float(sum(avg_list))/len(avg_list)),2)
    return result
        
@csrf_exempt
def map_char1(request):
    #return HttpResponse("test")
    if request.is_ajax() and request.method == 'GET':
        print request.GET
        if request.GET.get('value'):
            if request.GET.get('value')=="1":
                ret_val=hour_n(1)
                return HttpResponse(ret_val)
            elif request.GET.get('value')=="2":
                ret_val=hour_n(3)
                return HttpResponse(ret_val)
            elif request.GET.get('value')=="3":
                ret_val=hour_n(6)
                return HttpResponse(ret_val)
            elif request.GET.get('value')=="4":
                ret_val=hour_n(12)
                return HttpResponse(ret_val)
            elif request.GET.get('value')=="5":
                ret_val=hour_n(24)
                return HttpResponse(ret_val)
            else:
                print "-------------------------------error----------------------------"
    if request.is_ajax() and request.method == 'POST':
        
        if request.POST.get('data_date1') and request.POST.get('data_date2'):
            
            da1=request.POST.get('data_date1') 
            da2=request.POST.get('data_date2')
           
            ret_data=right_analysis(da1,da2)             # return json data to ret_data
            
            return HttpResponse(ret_data)
                          
    return render(request,"char_map_line.html")

def do_te(request):
    #return HttpResponse("test")
    return render(request,"test.html")