# encoding: utf-8
from __future__ import unicode_literals

import os

import simplejson as json
from jinja2 import Environment, FileSystemLoader, select_autoescape

HTML_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'html')
JINJA2_ENV = Environment(
    loader=FileSystemLoader(HTML_PATH),
    autoescape=select_autoescape(('html',))
)


class TemplateRender:
    """
    渲染k线图，买入卖出点，以及各种指标
    """

    def __init__(self, title, ohlc_df, order_history_df, format_str='%Y-%m-%d'):
        """
        全局只有一个echart，公用一个标题，k线图和买入卖出点是两个必须的图表
        :param title: 标题
        :param ohlc_df: k线图dataframe (index: datetime, column: [open, high, low, close])
        :param order_history_df:  买入卖出点dataframe (index: datetime, column: [amount, price, value])
        """

        self.indicator_list = []  # 需要显示的indicator，可以多个
        self.html = ''  # 渲染出来的html，调用render之后可用

        self.format_str = format_str
        self.title = title
        self.ohlc_df = self.__format_datetime__(ohlc_df.copy()).to_json(orient='index')
        self.order_history_df = self.__format_datetime__(order_history_df.copy()).to_json(orient='index')

        self.height = 1000  # echarts 默认高度

    def add_indicator(self, title, indicator_df):
        """
        各种指标的df，包括 cash/value
        :param title: 指标图表名称
        :param indicator_df: 指标的df (index: datetime, column: [indicator1, indicator2, ...])
        """
        grid = {
            'title': title,
            'indicator_df': self.__format_datetime__(indicator_df.copy()).to_json(orient='columns')
        }
        self.height += 500

        self.indicator_list.append(grid)

    def render(self):
        """
        将所有的block拼接
        :return: 拼接后的html
        """
        body_template = JINJA2_ENV.get_template('body_template.html')

        self.html = body_template.render(
            title=self.title,
            ohlc_df=self.ohlc_df,
            order_history_df=self.order_history_df,
            indicator_list=json.dumps(self.indicator_list),
            height=self.height
        )
        return self.html

    def save(self, file_path):
        """
        保存文件，并返回路径
        :param file_path: 文件路径
        :return: 保存之后的文件的路径
        """
        self.render()

        with open(file_path, 'w+') as html_file:
            html_file.write(self.html.encode('utf8'))
            return file_path

    def __format_datetime__(self, df):
        df_cp = df.copy()
        df_cp.index = df_cp.index.format(formatter=lambda x: x.strftime(self.format_str))
        return df_cp
