import pandas

from io import BytesIO, StringIO
from matplotlib.pyplot import axis, pie, savefig
from pcm_vulnerabilities_api import log_it


class QualysGraphClient:
    @staticmethod
    @log_it
    def render_basic_report_data_as_graph(data: str):
        '''Ingest qualys basic compliance report and render a pie chart graphic

        Parameters
        ----------
        data : str
            CSV report data that can be parsed by pandas

        Returns
        -------
        buffer : io.BytesIO
            PNG report data that has been graphed by matplotlib
        '''
        csv = pandas.read_csv(StringIO(data))
        sums = csv.groupby(['Account ID', 't_AppID'])[
            'Instances without an agent'].sum().nlargest(10)
        axis('equal')
        pie(sums, labels=sums.index)
        buffer = BytesIO(b'')  # blank buffer

        savefig(buffer, bbox_inches='tight')
        return buffer

    @staticmethod
    @log_it
    def render_basic_report_data_as_graph_v2(data: str):
        '''Ingest qualys basic compliance report and render a pie chart graphic

        Parameters
        ----------
        data : list
            CSV report data that can be parsed by pandas

        Returns
        -------
        buffer : io.BytesIO
            PNG report data that has been graphed by matplotlib
        '''
        buffer: StringIO = StringIO(data)
        csv = pandas.read_csv(buffer)
        agent_status = {
            'STATUS_NO_AGENT': 1,
            'STATUS_ACTIVE': 0,
            'STATUS_INACTIVE': 1
        }
        sums = csv.replace({'qualys_agent_status': agent_status}).groupby(
            ['account_id', 't_appid'])['qualys_agent_status'].sum().nlargest(10)
        axis('equal')
        pie(sums, labels=sums.index)
        image = BytesIO(b'')  # blank buffer

        savefig(image, bbox_inches='tight')
        return image
