/*
Markdown controller to view and update journal entries.

@copyright (c) Copyright 2013-2017 Dorian Pula
@license AGPL v3
@author Dorian Pula [dorian.pula@amber-penguin-software.ca]
*/


import {h, Component} from 'preact';  /** @jsx h*/

import PropTypes from 'prop-types';
import {observer} from 'mobx-observer';

import markdown from 'markdown-it';
import highlighter from 'highlight.js';

import {pageStore, siteStore} from '../stores';
import {themeStore} from '../themes/store';

export class MarkdownBlock extends Component {
  static get propTypes() {
    return {
      id: PropTypes.string,
      slug: PropTypes.string,
      content: PropTypes.string,
      styler: PropTypes.object,
    }
  }

  render() {
    let md = markdown({
      html: true,
      highlight: (code_) => {
        return highlighter.highlightAuto(code_).value;
      }
    });
    let rawMarkup = md.render(this.props.content || '');

    return (
      <span
        id={ this.props.id }
        dangerouslySetInnerHTML={{__html: rawMarkup}}
        style={ this.props.styler } />
    );
  }
}


@observer
export class PageBlock extends Component {
  // TODO: Add support for HTML / Markdown
  static get propTypes() {
    return {
      location: PropTypes.object.isRequired,
      match: PropTypes.object,
      styler: PropTypes.object,
    }
  }

  componentDidMount() {
    let pageToLoad = this.props.match.params.pageId;
    if (pageToLoad === undefined) {
      pageStore.fetchPage(siteStore.landingPage);
    }

    pageStore.fetchPage(pageToLoad);
  }

  componentWillReceiveProps(nextProps) {
    const {match} = this.props;
    const pageToLoad = nextProps.match.params.pageId;
    if (match.params.pageId !== pageToLoad) {

      if (pageToLoad === undefined) {
        pageStore.fetchPage(siteStore.landingPage);
      }

      pageStore.fetchPage(pageToLoad);
    }
  }

  render() {
    // TODO: Figure out a better way to communicate styles to components.
    const pageLocation = {
      gridRow: '3 / 8',
      gridColumn: '3 / 9',
    };

    const backdropColor = themeStore.currentTheme === 'daytime' ? '#777777' : '#d0d0d0';

    const pageStyle = {
      backgroundColor: backdropColor,

      borderRadius: '25px',
      border: '1px solid #111111',
      boxShadow: '5px 5px #111111',

      padding: '30px',
      margin: '15px',
    };

    return (
      <MarkdownBlock
        slug={ pageStore.slug }
        content={ pageStore.content }
        styler={{ ...pageLocation, ...pageStyle }} />
    );
  }
}
