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

from wordcloud import WordCloud
import cv2
import matplotlib.pyplot as plt
import bottom_function.data_read as dr
from bottom_function import normalization as norm


# import json
# from flask import Flask
# from flask import request
# from flask_cors import CORS


def portrait_plot(datatype, starttime, endtime):
    n_data = dr.read_data(datatype=datatype, starttime=starttime, endtime=endtime)
    if n_data.empty:
        return 0
    query_data = ''
    for q in n_data['query']:
        str_q = str(q)
        query_data = query_data + "," + str_q

    cut_text = norm.remove_special_characters(query_data)

    color_mask = cv2.imread('/home/work/semantic_platform_DAS/bottom_function/data/gree_logo.jpg')

    cloud = WordCloud(
        # 设置字体，不指定就会出现乱码
        font_path="./bottom_function/data/msyh.ttf",
        # font_path=path.join(d,'simsun.ttc'),
        font_step=1,
        width=720,
        height=720,
        # 设置背景色
        background_color='white',
        # 词云形状
        mask=color_mask,
        # 允许最大词汇
        max_words=10000,
        # 最大号字体
        max_font_size=50,
        min_font_size=5
    )

    wCloud = cloud.generate(cut_text)
    # wCloud.to_file('../data/word_cloud/cloud.jpg')

    plt.imshow(wCloud, interpolation='bilinear')

    plt.axis('off')
    til = starttime + ' to ' + endtime + ' ' + datatype + ' user portrait of word cloud'
    plt.title(til)
    path = '/roobo/soft/phpmyadmin/plot_user.jpg'
    wCloud.to_file(path)
    # plt.savefig(path)
    return 'http://120.79.171.145:8000/plot_user.jpg'

# portrait_plot(datatype='all', starttime='2018-12-28 00:00:00', endtime='2018-12-29 00:00:00')

# app = Flask(__name__)
# CORS(app, supports_credentials=True)
#
#
# @app.route('/SPDAS/user_portrait_analysis1', methods=['POST'])
# def domain():
#     param = ({"data_type": [{"value": "control"}, {"value": "application"}, {"value": "all"}],
#               "time": "2019.01.01 00:00:00/2019.01.02 00:00:00"})
#     return json.JSONEncoder().encode(param)
#
#
# @app.route('/SPDAS/user_portrait_analysis2', methods=['POST'])
# def domain_form():
#     # 需要从request对象读取表单内容：
#     data = request.get_data()
#     json_re = json.loads(data)
#
#     datatype = json_re['data_type']
#     m_time = json_re['time']
#     str_time = str(m_time)
#     m_time = str_time.split('/')
#     starttime = m_time[0]
#     endtime = m_time[1]
#     image_path = portrait_plot(datatype=datatype, starttime=starttime, endtime=endtime)
#     path = {"user_image": image_path}
#     return json.JSONEncoder().encode(path)
#
#
# if __name__ == '__main__':
#     app.run(debug=True, host='10.7.19.129', port=5000)
