# -*- coding: utf-8 -*-
# author：Li Mingjie time:2019/2/28
# Brief:Response Error Analysis

import pandas as pd
import matplotlib.pyplot as plt
import bottom_function.data_read as dr


def error_data_statistics_plot(datatype, starttime, endtime, graphtype):
    if datatype == 'control':
        datatype = 'error_control'
    else:
        datatype = 'error_application'
    csv_data = pd.DataFrame()
    csv_data = dr.read_data(datatype=datatype, starttime=starttime, endtime=endtime)
    print(len(csv_data))
    csv_data.drop_duplicates(subset='query', keep='first', inplace=True)
    csv_data = csv_data.reset_index(drop=True)
    error_dict = {}
    for i in range(len(csv_data)):
        error_code = "error " + str(csv_data.ix[i]['code'])
        if error_code in error_dict.keys():
            error_dict[error_code] += 1
        else:
            error_dict.update({error_code: 1})

    plt.figure(figsize=(10, 8))
    if graphtype == 'pie':
        e = []
        code_other = 0
        for j in error_dict.keys():
            if j != "error 501":
                e.append(0.1)
                code_other += error_dict[j]
            else:
                e.append(0)

        labels = ["error 501", "others"]
        fracs = [error_dict["error 501"], code_other]

        v_sum = sum(fracs)
        v_data = fracs
        for fx in range(0, len(fracs)):
            v_data[fx] = fracs[fx] / v_sum * 100
        fracs = v_data
        explode = e[:(len(fracs))]
        if sum(e[len(fracs):]) > 0:
            explode[-1] = 0.1
        plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.2f%%', shadow=True, startangle=90)

    if graphtype == 'bar':
        name_list = list(error_dict.keys())
        num_list = list(error_dict.values())
        plt.bar(range(len(num_list)), num_list)
        plt.xticks(range(len(name_list)), name_list)
        plt.ylabel('Number', fontsize=12, labelpad=5)
        for x, y in zip(range(len(num_list)), num_list):
            plt.text(x, y, '%d' % y, ha='center', va='bottom', fontsize=9)

    plt.title(str(starttime) + ' to ' + str(endtime) + ' ' + datatype + ' response analysis of ' + graphtype + ' graph',
              fontsize=15)
    plt.tight_layout(5)
    path = '/roobo/soft/phpmyadmin/response_error.jpg'
    plt.savefig(path)
    return 'http://120.79.171.145:8000/response_error.jpg'
