from .message import SaasMessage
from .message import ACT

import urllib


class SaasDeleteDocument(object):
    Url = None

    def __init__(self, url):
        self.Url = url

    def to_json(self, context):
        return {'url': self.Url}


class SaasDeleteMessage(SaasMessage):
    IsSpecial = False

    def __init__(self, prefix=0, url=None, request=None):
        """
        Deletes document with url or documents corresponding request
        Examples:
            SaasDeleteMessage(prefix, url='http://some_url')
            or
            SaasDeleteMessage(prefix, request='sometext&...')
        :param prefix: for prefixed index only, else 0
        :type url: str or None
        :param request: request to search for deletion, without 'text='
        :type request: str or None
        :return:
        """
        if self.IsSpecial:
            self.Request = request
        else:
            self.Request = urllib.quote_plus(request) if request is not None else None
        if prefix and request and 'kps=' not in request:
            self.Request += '&kps=' + str(prefix)
        action = ACT.delete
        super(SaasDeleteMessage, self).__init__(action=action, prefix=prefix, document=None)
        if url is not None:
            self.Document = SaasDeleteDocument(url)

    def gen_document(self, **kwargs):
        self.Document = SaasDeleteDocument(**kwargs)


class SaasDeleteKpsMessage(SaasDeleteMessage):
    IsSpecial = True

    def __init__(self, prefix):
        """
        Deletes all documents for prefix in prefixed index
        :type prefix: int
        :return:
        """
        request = '$remove_kps$'
        super(SaasDeleteKpsMessage, self).__init__(prefix=prefix, url=None, request=request)


class SaasDeleteAllIndexMessage(SaasDeleteMessage):
    IsSpecial = True

    def __init__(self):
        """
        Deletes all documents in index
        :return:
        """
        request = '$remove_all$'
        super(SaasDeleteAllIndexMessage, self).__init__(request=request)
