#!/usr/bin/env python
# -*- coding: utf-8 -*-
import slack_sdk
from aws_xray_sdk.core import xray_recorder as xray
from datetime import date, timedelta
from fivepillars.models import VPDRecords
from iobot.views import ModalView
from iobot.models import IOBotObject
from iobot.xray import put_metadata
from psi_logger import logger
from psi_logger import log as _log
from typing import Dict



@xray.capture()
class VPDReportView(ModalView):
    """ Generate a VPD Report View

    >>> os.environ['STACK_NAME'] = 'iobots-stack'

    >>> testing.export_secret_arns(os.environ['STACK_NAME'])

    >>> slack_client = slack_sdk.WebClient(token=testing.slack_bearer_token())

    >>> data = VPDRecords.get_vpd(t_appids=['SVC02109'],
    ...                           records=VPDRecords.to_dataframe(
    ...                             'tests/data/vpd_index_report.csv'))

    >>> records: VPDRecords = VPDRecords.to_vpd_records(data=data)

    >>> view = VPDReportView(log, slack_client, records=records)

    >>> view.Blocks()  # noqa: E501
    [{'type': 'section', 'block_id': 'vpd_report_range', 'text': {'type': 'mrkdwn', 'text': '*FivePillars VPD Report*'}, 'accessory': {'type': 'overflow', 'action_id': 'vpd_report_range', 'options': [{'text': {'type': 'plain_text', 'emoji': True, 'text': '* Last 30 Days *'}, 'value': 'view^GetReportRange^-30'}, {'text': {'type': 'plain_text', 'emoji': True, 'text': '* Last 60 Days *'}, 'value': 'view^GetReportRange^-60'}, {'text': {'type': 'plain_text', 'emoji': True, 'text': '* Last 90 Days *'}, 'value': 'view^GetReportRange^-90'}, {'text': {'type': 'plain_text', 'emoji': True, 'text': '* Last 120 Days *'}, 'value': 'view^GetReportRange^-120'}]}}, {'type': 'divider'}, {'type': 'divider'}, {'type': 'section', 'block_id': 'fivepillar_vpd_report_action-SVC02109-None', 'text': {'type': 'mrkdwn', 'text': '*SVC02109* (None)\\n'}}, {'type': 'actions', 'block_id': 'fivepillar_vpd_report_detail-SVC02109-None', 'elements': [{'type': 'button', 'action_id': 'fivepillar_vpd_report_detail-SVC02109-None', 'text': {'type': 'plain_text', 'text': 'View Details', 'emoji': True}, 'value': 'view^SVC02109^None'}]}]

    >>> testing.unexport_secret_arns()

    >>> del os.environ['STACK_NAME']
    """
    @xray.capture()
    @logger.log
    def __init__(self,
                 log = _log,
                 slack_client: slack_sdk.WebClient = None,
                 records: VPDRecords = [],
                 callback_id: str = "FivePillarsVPDReportView",
                 title: str = "FivePillars VPD Report",
                 close: str = "Close",
                 blocks: list = None,
                 metadata: dict = None,
                 pages: list = None,
                 request: dict = None) -> None:

        super().__init__(log,
                         slack_client,
                         callback_id=callback_id,
                         title=title,
                         close=close,
                         blocks=blocks,
                         metadata=metadata,
                         request=request)

        self.add_block({
            "type": "section",
            "block_id": "vpd_report_range",
            "text": {
                "type": "mrkdwn",
                "text": f"*{title}*"
            },
            "accessory": {
                "type": "overflow",
                "action_id": "vpd_report_range",
                "options": [
                    {
                        "text": {
                            "type": "plain_text",
                            "emoji": True,
                            "text": "* Last 30 Days *"
                        },
                        "value": "view^GetReportRange^-30"
                    },
                    {
                        "text": {
                            "type": "plain_text",
                            "emoji": True,
                            "text": "* Last 60 Days *"
                        },
                        "value": "view^GetReportRange^-60"
                    },
                    {
                        "text": {
                            "type": "plain_text",
                            "emoji": True,
                            "text": "* Last 90 Days *"
                        },
                        "value": "view^GetReportRange^-90"
                    },
                    {
                        "text": {
                            "type": "plain_text",
                            "emoji": True,
                            "text": "* Last 120 Days *"
                        },
                        "value": "view^GetReportRange^-120"
                    }
                ]
            }
        })

        self.add_block({
            "type": "divider"
        })

        for record in records:
            log.debug(f"record: {record.to_json()}")

            self.add_block({
                "type": "divider"
            })

            self.add_block({
                "type": "section",
                "block_id": f"fivepillar_vpd_report_action-{record.get('t_appid')}-{record.get('report_date')}",
                "text": {
                    "type": "mrkdwn",
                    "text": f"*{record.get('t_appid')}* ({record.get('vpd')})\n"
                }
            })
            self.add_block({
                "type": "actions",
                "block_id": f"fivepillar_vpd_report_detail-{record.get('t_appid')}-{record.get('report_date')}",
                "elements": [
                    {
                        "type": "button",
                        "action_id": f"fivepillar_vpd_report_detail-{record.get('t_appid')}-{record.get('report_date')}",
                        "text": {
                            "type": "plain_text",
                            "text": "View Details",
                            "emoji": True
                        },
                        "value": f"view^{record.get('t_appid')}^{record.get('report_date')}"
                    }
                ]
            })


class CloudabilityCostsReportView(ModalView):
    """[summary]

    Args:
        ModalView ([type]): [description]

    >>> data = IOBotObject(**{"cloudability_cost_t_AppID":1, "cloudability_cost_environments":1, "cloudability_cost_report_type":1})
    >>> view = CloudabilityCostsReportView(None,None,data=data)
    >>> len(view.Blocks()) > 1
    True
    """
    @xray.capture()
    @logger.log
    def __init__(self, log, slack_client, data=None, callback_id="CloudabilityCostsReportView", title="Cloudability-CostsReport", close="Cancel", blocks=None, request: Dict = None, metadata=None) -> None:
        super().__init__(log, slack_client, callback_id=callback_id,
                         title=title, close=close, blocks=blocks, metadata=metadata, request=request)

        self.add_submit_button(title="Submit")
        #action_id = slater_selected_applications
        
        pre_data = [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": "Date Range:"
                }
            },
            {
                "type": "actions",
                "block_id": 'cloudability_cost_datepicker',
                "elements": [
                    {
                        "type": "datepicker",
                        "action_id": 'cloudability_cost_datepicker_start',
                        "initial_date": (date.today()-timedelta(days=30)).isoformat(),
                        "placeholder": {
                            "type": "plain_text",
                            "text": "Start Date",
                            "emoji": True
                        }
                    },
                    {
                        "type": "datepicker",
                        "action_id": 'cloudability_cost_datepicker_end',
                        "initial_date": date.today().isoformat(),
                        "placeholder": {
                            "type": "plain_text",
                            "text": "End Date",
                            "emoji": True
                        }
                    }
                ]
            }
        ]

        pre_data.extend(data.to_slack_modal_form(slack_element_type_map = {'cloudability_cost_t_AppID':'multi_external_select', 'cloudability_cost_environments':'multi_static_select', 'cloudability_cost_report_type':'static_select'}, slack_element_options = {'cloudability_cost_t_AppID': { 'action_id': 'slater_selected_applications', 'max_selected_items': 5 }, 'cloudability_cost_environments': { 'options': [{'prd':'0'},{'nonprd':'1'},{'tst':'2'}], 'transform': [{'0':'prd'},{'1':'nonprd'},{'2':'tst'}], 'max_selected_items': 5 }, 'cloudability_cost_report_type': { 'options': [{'Cost Blended':'0'},{'Cost Unblended':'1'}], 'transform': [{'0':'Cost Blended'},{'1':'Cost Unblended'}]}}))
        #pre_data.extend(data.to_slack_modal_form(slack_element_type_map = {'cloudability_cost_t_AppID':'multi_static_select', 'cloudability_cost_environments':'multi_static_select', 'cloudability_cost_report_type':'static_select'}, slack_element_options = {'cloudability_cost_t_AppID': { 'options': [{'svc01175':'0'},{'svc01445':'1'}], 'transform': [{'0':'svc01175'},{'1':'svc01445'}]}, 'cloudability_cost_environments': { 'options': [{'prd':'0'},{'non-prd':'1'},{'test':'2'}], 'transform': [{'0':'prd'},{'1':'non-prd'},{'2':'test'}] }, 'cloudability_cost_report_type': { 'options': [{'Cost Blended':'0'},{'Cost Unblended':'1'}], 'transform': [{'0':'Cost Blended'},{'1':'Cost Unblended'}]}}))
        
        pre_data.append({
            "type": "divider"
        })

        pre_data.append({
            "type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "<https://app.cloudability.com/#/dashboards|Cloudability>"
			}
        })

        pre_data.append({
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "<https://forms.office.com/r/e3CnGxTdU5|Feedback Form>"
			}
		})
        put_metadata("blocks", pre_data)
        self.add_blocks(pre_data)


class CloudabilityCostsResponseView(ModalView):
    """[summary]

    Args:
        ModalView ([type]): [description]

    >>> data = {"results": [{"tappid": "svc01445", "env": "prd", "cost": "108561.91", "delta": 3.75}, {"tappid": "svc01175", "env": "prd", "cost": "31339.31", "delta": -9.92}], "start_date": "03/21", "end_date": "04/21", "date_title":"Report for 03/21-04/21 compared to 03/21-04/21"}
    >>> view = CloudabilityCostsResponseView(None,None,data=data)
    >>> len(view.Blocks()) > 1
    True
    
    """
    @xray.capture()
    @logger.log
    def __init__(self, log, slack_client, data=None, callback_id="CloudabilityCostsResponseView", title="Cloudability-CostsReport", close="Cancel", blocks=None, request: Dict = None, metadata=None) -> None:
        super().__init__(log, slack_client, callback_id=callback_id,
                         title=title, close=close, blocks=blocks, metadata=metadata, request=request)

        # self.add_submit_button(title="Submit")
        # action_id = slater_selected_applications
        blocks = []
        if data.get('none'):
            blocks.append({
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": f":cry: {data.get('none')} :cry:"
                }
            })
        else:
            blocks.append({
                "type": "divider"
            })
            blocks.append({
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": f"*{data['date_title']}*"
                }
            })
            
            # tag1_len = self.max_len_dict(data['results'], 'tag1')
            # tag2_len = self.max_len_dict(data['results'], 'tag2')
            # cost_len = self.max_len_dict(data['results'], 'cost')
            # delta_len = self.max_len_dict(data['results'], 'delta')


            blocks.append({
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": f"{'*App*'}          |  {'*Env*'}  |   {'*Cost*'}   |  {'*Delta From Previous*'}"
                }
            })
            
            
            for x in data['results']:
                dsign = '$'
                percent = '%'
                if x['delta'] == 'No Data':
                    arrow = ':cry:'
                    dsign = ''
                    percent = ''
                elif x['delta'] <= 0:
                    arrow = ':arrow_down:'
                else:
                    arrow = ':arrow_up:'

                text = f"{x['tappid']} |  {x['env']}  | {dsign+x['cost']} |  {arrow + str(x['delta'])+percent}"
                blocks.append({
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": text
                    }
                })
                
        
        blocks.append({
            "type": "divider"
        })

        blocks.append({
            "type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "<https://app.cloudability.com/#/dashboards|Cloudability>"
			}
        })

        blocks.append({
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "<https://forms.office.com/r/e3CnGxTdU5|Feedback Form>"
			}
		})

        put_metadata("blocks", blocks)
        self.add_blocks(blocks)

    def max_len_dict(self, filt_list:list, filt_key:str):
        return len(str(max(filt_list, key = lambda sub: len(str(sub[filt_key])) if sub[filt_key] is not None else 0)[filt_key]))

    def center_text(self, title:str, width:int):
        if not width%2:
            width += 1
        return str.center(title, width, ' ')
    
    def left_text(self, title:str, width:int):
        return title.ljust(width, ' ')