from eolymp.content.content_service_http import ContentServiceClient
from eolymp.content.content_service_pb2 import ListFragmentsInput, UpdateFragmentInput, CreateFragmentInput
from eolymp.content.fragment_pb2 import Fragment
from eolymp.ecm.content_pb2 import Content

from peolymp.abstract import AbstractAPI


class ContentAPI(AbstractAPI):
    def __init__(self, space):
        super(ContentAPI, self).__init__(space)
        self.client = ContentServiceClient(self.http_client, url=self.get_url())
        self.pages = self.get_pages()

    def get_pages(self):
        def __get_pages(offset, size):
            return self.client.ListFragments(request=ListFragmentsInput(offset=offset, size=size))

        return self.get_many(__get_pages)

    def get_id(self, path):
        for page in self.pages:
            if page.path == path:
                return page.id
        return None

    def create_page(self, contest_id, code, title, latex="", markdown="", locale="en", labels=None):
        if labels is None:
            labels = []
        self.client = ContentServiceClient(self.http_client, url=self.get_url() + "/contests/" + contest_id)
        if latex:
            content = Content(latex=latex)
        if markdown:
            content = Content(markdown=markdown)
        fragment = Fragment(
            path=code,
            locale=locale,
            title=title,
            content=content,
            labels=labels
        )
        self.pages = self.get_pages()
        id = self.get_id(code)
        if id:
            return self.client.UpdateFragment(UpdateFragmentInput(fragment_id=id, fragment=fragment))
        else:
            return self.client.CreateFragment(CreateFragmentInput(fragment=fragment))
