<reponame>notpushkin/mkdocutils
import logging
from mkdocutils.docutils import to_html
from pathlib import Path
from urllib.parse import urljoin, urlparse

from mkdocutils.structure.toc import get_toc
from mkdocutils.utils import (
    get_build_date,
    get_markdown_title,
    meta,
    warning_filter,
)

log = logging.getLogger(__name__)
log.addFilter(warning_filter)


class Page:
    def __init__(self, title, file, config):
        file.page = self
        self.file = file
        self.title = title

        # Navigation attributes
        self.parent = None
        self.children = None
        self.previous_page = None
        self.next_page = None
        self.active = False

        self.is_section = False
        self.is_page = True
        self.is_link = False

        self.update_date = get_build_date()

        self._set_canonical_url(config.get('site_url', None))
        self._set_edit_url(
            config.get('repo_url', None),
            config.get('edit_uri', None),
        )

        # Placeholders to be filled in later in the build process.
        self.source = None
        self.content = None
        self.toc = []
        self.meta = {}

    def __eq__(self, other):
        return (
            isinstance(other, self.__class__) and
            self.title == other.title and
            self.file == other.file
        )

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        title = "'{}'".format(self.title) if (
            self.title is not None
        ) else '[blank]'
        return "Page(title={}, url='{}')".format(title, self.abs_url or self.file.url)

    def _indent_print(self, depth=0):
        return '{}{}'.format('    ' * depth, repr(self))

    def _get_active(self):
        """ Return active status of page. """
        return self.__active

    def _set_active(self, value):
        """ Set active status of page and ancestors. """
        self.__active = bool(value)
        if self.parent is not None:
            self.parent.active = bool(value)

    active = property(_get_active, _set_active)

    @property
    def is_index(self):
        return self.file.name == 'index'

    @property
    def is_top_level(self):
        return self.parent is None

    @property
    def is_homepage(self):
        return self.is_top_level and self.is_index and self.file.url == '.'

    @property
    def url(self):
        return '' if self.file.url == '.' else self.file.url

    @property
    def ancestors(self):
        if self.parent is None:
            return []
        return [self.parent] + self.parent.ancestors

    def _set_canonical_url(self, base):
        if base:
            if not base.endswith('/'):
                base += '/'
            self.canonical_url = urljoin(base, self.url)
            self.abs_url = urlparse(self.canonical_url).path
        else:
            self.canonical_url = None
            self.abs_url = None

    def _set_edit_url(self, repo_url, edit_uri):
        if repo_url and edit_uri:
            src_path = self.file.src_path.replace('\\', '/')
            self.edit_url = urljoin(repo_url, edit_uri + src_path)
        else:
            self.edit_url = None

    def read_source(self, config):
        source = config['plugins'].run_event(
            'page_read_source', page=self, config=config,
        )
        if source is None:
            try:
                with open(self.file.abs_src_path, 'r', encoding='utf-8-sig', errors='strict') as f:
                    source = f.read()
            except OSError:
                log.error('File not found: {}'.format(self.file.src_path))
                raise
            except ValueError:
                log.error(
                    'Encoding error reading file: {}'.format(
                        self.file.src_path,
                    ),
                )
                raise

        self.source, self.meta = meta.get_data(source)
        self._set_title()

    def _set_title(self):
        """
        Set the title for a Markdown document.

        Check these in order and use the first that returns a valid title:
        - value provided on init (passed in from config)
        - value of metadata 'title'
        - content of the first H1 in Markdown content
        - convert filename to title
        """
        if self.title is not None:
            return

        if 'title' in self.meta:
            self.title = self.meta['title']
            return

        title = get_markdown_title(self.source)

        if title is None:
            if self.is_homepage:
                title = 'Home'
            else:
                title = self.file.name.replace('-', ' ').replace('_', ' ')
                # Capitalize if the filename was all lowercase, otherwise leave it as-is.
                if title.lower() == title:
                    title = title.capitalize()

        self.title = title

    def render(self, config, files):
        """
        Convert the Markdown source file to HTML as per the config.
        """

        parts = to_html(
            source=self.source,
            src_path=self.file.src_path,
            extension=self.file.get_extension(),
        )
        self.content = parts
        self.toc = get_toc([])  # TODO

import logging
from mkdocutils.docutils import to_html
from pathlib import Path
from urllib.parse import urljoin, urlparse

from mkdocutils.structure.toc import get_toc
from mkdocutils.utils import (
    get_build_date,
    get_markdown_title,
    meta,
    warning_filter,
)

log = logging.getLogger(__name__)
log.addFilter(warning_filter)


class Page:
    def __init__(self, title, file, config):
        file.page = self
        self.file = file
        self.title = title

        # Navigation attributes
        self.parent = None
        self.children = None
        self.previous_page = None
        self.next_page = None
        self.active = False

        self.is_section = False
        self.is_page = True
        self.is_link = False

        self.update_date = get_build_date()

        self._set_canonical_url(config.get('site_url', None))
        self._set_edit_url(
            config.get('repo_url', None),
            config.get('edit_uri', None),
        )

        # Placeholders to be filled in later in the build process.
        self.source = None
        self.content = None
        self.toc = []
        self.meta = {}

    def __eq__(self, other):
        return (
            isinstance(other, self.__class__) and
            self.title == other.title and
            self.file == other.file
        )

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        title = "'{}'".format(self.title) if (
            self.title is not None
        ) else '[blank]'
        return "Page(title={}, url='{}')".format(title, self.abs_url or self.file.url)

    def _indent_print(self, depth=0):
        return '{}{}'.format('    ' * depth, repr(self))

    def _get_active(self):
        """ Return active status of page. """
        return self.__active

    def _set_active(self, value):
        """ Set active status of page and ancestors. """
        self.__active = bool(value)
        if self.parent is not None:
            self.parent.active = bool(value)

    active = property(_get_active, _set_active)

    @property
    def is_index(self):
        return self.file.name == 'index'

    @property
    def is_top_level(self):
        return self.parent is None

    @property
    def is_homepage(self):
        return self.is_top_level and self.is_index and self.file.url == '.'

    @property
    def url(self):
        return '' if self.file.url == '.' else self.file.url

    @property
    def ancestors(self):
        if self.parent is None:
            return []
        return [self.parent] + self.parent.ancestors

    def _set_canonical_url(self, base):
        if base:
            if not base.endswith('/'):
                base += '/'
            self.canonical_url = urljoin(base, self.url)
            self.abs_url = urlparse(self.canonical_url).path
        else:
            self.canonical_url = None
            self.abs_url = None

    def _set_edit_url(self, repo_url, edit_uri):
        if repo_url and edit_uri:
            src_path = self.file.src_path.replace('\\', '/')
            self.edit_url = urljoin(repo_url, edit_uri + src_path)
        else:
            self.edit_url = None

    def read_source(self, config):
        source = config['plugins'].run_event(
            'page_read_source', page=self, config=config,
        )
        if source is None:
            try:
                with open(self.file.abs_src_path, 'r', encoding='utf-8-sig', errors='strict') as f:
                    source = f.read()
            except OSError:
                log.error('File not found: {}'.format(self.file.src_path))
                raise
            except ValueError:
                log.error(
                    'Encoding error reading file: {}'.format(
                        self.file.src_path,
                    ),
                )
                raise

        self.source, self.meta = meta.get_data(source)
        self._set_title()

    def _set_title(self):
        """
        Set the title for a Markdown document.

        Check these in order and use the first that returns a valid title:
        - value provided on init (passed in from config)
        - value of metadata 'title'
        - content of the first H1 in Markdown content
        - convert filename to title
        """
        if self.title is not None:
            return

        if 'title' in self.meta:
            self.title = self.meta['title']
            return

        title = get_markdown_title(self.source)

        if title is None:
            if self.is_homepage:
                title = 'Home'
            else:
                title = self.file.name.replace('-', ' ').replace('_', ' ')
                # Capitalize if the filename was all lowercase, otherwise leave it as-is.
                if title.lower() == title:
                    title = title.capitalize()

        self.title = title

    def render(self, config, files):
        """
        Convert the Markdown source file to HTML as per the config.
        """

        parts = to_html(
            source=self.source,
            src_path=self.file.src_path,
            extension=self.file.get_extension(),
        )
        self.content = parts
        self.toc = get_toc([])  # TODO
# Navigation attributes # Placeholders to be filled in later in the build process. Return active status of page. Set active status of page and ancestors. Set the title for a Markdown document.          Check these in order and use the first that returns a valid title:         - value provided on init (passed in from config)         - value of metadata 'title'         - content of the first H1 in Markdown content         - convert filename to title # Capitalize if the filename was all lowercase, otherwise leave it as-is. Convert the Markdown source file to HTML as per the config. # TODO