# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from dateutil import tz
from collections import namedtuple

REQUIRED_PARAMS = ('sources', 'destinations', 'protocol', 'ports', )
OPTIONAL_PARAMS = ('locations', 'until', 'comment', 'id', 'rule_id', 'type', 'status', 'author', 'task', 'sibdiscussion', 'responsiblediscussion',
                   'system', 'added', 'updated', 'responsibles', 'can_approve', 'can_reject')

RuleRequestSpec = namedtuple('RuleRequestSpec', REQUIRED_PARAMS + OPTIONAL_PARAMS)
RuleRequestSpec.__new__.__defaults__ = (None, ) * len(OPTIONAL_PARAMS)


class RuleRequest(RuleRequestSpec):
    __slots__ = ()

    def request_dict(self):
        if self.until is not None:
            until = self.until.replace(tzinfo=tz.tzlocal()) if self.until.tzinfo is None else self.until
            until_str = until.astimezone(tz.UTC).isoformat()
        else:
            until_str = self.until
        return {
            'sources': self.sources,
            'destinations': self.destinations,
            'protocol': self.protocol.value,
            'locations': [l.value for l in self.locations] if self.locations else None,
            'ports': [str(pr) for pr in self.ports],
            'until': until_str,
            'comment': self.comment
        }
