
from .attribute import AttributesOwner
from .zone import ZonesOwner

import json
import time
from .context import ToJsonContext


class SaasDocument(AttributesOwner, ZonesOwner):
    __slots__ = ('url', 'body',
                 'inddoc', 'realtime',
                 'check_only_before_reply',
                 'mime_type', 'charset',
                 'language', 'language2',
                 'language_default', 'deadline_min_utc',
                 'version', 'modification_timestamp',
                 'update_type', 'attributes', 'children',
                 'annotations')

    def __init__(self, url, body=None, inddoc=None, realtime=None, check_only_before_reply=None,
                 mime_type='text/plain', charset='utf8', language='ru', language2='ru', language_default='ru',
                 deadline_min_utc=None, version=None, modification_timestamp=None, update_type=None):
        self.url = url
        self.body = body
        self.inddoc = inddoc
        self.realtime = realtime
        self.check_only_before_reply = check_only_before_reply
        self.mime_type = mime_type
        self.charset = charset
        self.language = language
        self.language2 = language2
        self.language_default = language_default
        self.deadline_min_utc = deadline_min_utc
        self.version = version
        self.modification_timestamp = modification_timestamp
        self.update_type = update_type
        self.attributes = {}
        self.children = {}
        self.annotations = []

    def set_ttl(self, minutes):
        self.deadline_min_utc = int(time.time() / 60 + minutes)

    def __str__(self):
        return json.dumps(self.to_json(ToJsonContext()), indent=4)

    def __get_options(self):
        option_names = ('realtime',
                        'check_only_before_reply',
                        'mime_type', 'charset',
                        'language', 'language2',
                        'language_default', 'deadline_min_utc',
                        'version', 'modification_timestamp', 'update_type')
        options = {}
        for option_name in option_names:
            value = getattr(self, option_name)
            if value is not None:
                options[option_name] = value
        return options

    def to_json(self, context):
        json_repr = {
            'url': self.url,
            'options': self.__get_options()
        }

        for field in ('body', 'inddoc'):
            value = getattr(self, field)
            if value:
                json_repr[field] = context.serialize_text(value)

        json_repr.update(self.attributes_to_json(context))
        if self.children:
            json_repr.update(self.zones_to_json(context))
        if self.annotations:
            json_repr.update({'annotations': {'type': '#a', 'value': [a.to_json(context) for a in self.annotations]}})

        return json_repr
