import os

from startrek_client import Startrek
from datetime import datetime
from datetime import timedelta

from saas.tools.devo.devo.core.plugins import BasePlugin
from saas.tools.devo.devo.plugins import ROOT_PATH
from jinja2 import Environment, FileSystemLoader
from library.python import resource

class Reminder(BasePlugin):
    title = u'Reminder'
    desc = u'Monitoring of forgotten issues in SAASSUP'

    def setup(self):
        self.startrek = Startrek(
                                 useragent=self.config.get('st', 'user_login'),
                                 base_url=self.config.get('st', 'base_url'),
                                 token=os.environ.get('ST_TOKEN')
                                )

        self.env = Environment()
        template_key = '/devo/plugins/reminder/templates/reminder.tpl'
        self.template = resource.find(template_key).decode("utf-8")

    def main(self):
        date_from = "2019-12-01"
        delta = timedelta(days=int(self.config.get('plugins.reminder', 'days')))
        date_to = (datetime.today() - delta).strftime("%Y-%m-%d")

        st_query = 'Resolution: empty() ' + \
                   'Updated: "%s".."%s" ' + \
                   'Queue: SAASSUP ' + \
                   'Status: open, needInfo, inProgress ' + \
                   '"Sort by": Updated ASC '

        st_query = st_query % (date_from, date_to)

        issues = self.startrek.issues.find(st_query)

        keys = [issue.key for issue in issues]
        print("Tickets without actions:")
        print(keys)

        for issue in issues:
            if issue.assignee is not None:
                need_responsibled = issue.updatedBy.login == 'robot-devo'
                if need_responsibled:
                    self._ping_responsibled(issue)
                else:
                    self._ping_assignee(issue)
            else:
                self._ping_responsibled(issue, need="назначить исполнителя")

    def _ping_responsibled(self, issue, need="обратить внимание на задачу"):
        template = self.env.from_string(self.template)
        text = template.render(
            whom="ответственного",
            name=self.config.get('plugins.reminder', 'responsibled_name'),
            need=need
        )
        issue.comments.create(text=text, summonees=[self.config.get('plugins.reminder', 'responsibled_login')])

    def _ping_assignee(self, issue, need="обратить внимание на задачу. Если нужна помощь - дай знать"):
        template = self.env.from_string(self.template)
        text = template.render(
            whom="исполнителя",
            name=issue.assignee.display.split()[0],
            need=need
        )
        issue.comments.create(text=text, summonees=[issue.assignee.login])

