/*
Page editor component

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

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

import {observer} from 'mobx-observer';

import {UnControlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/mode/markdown/markdown';

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


@observer
export class PageEditor extends Component {
  // TODO: Add support for HTML / Markdown
  // TODO: Add support for changing titles.
  constructor(props) {
    super(props);
    this.handleUpdateCode = this.handleUpdateCode.bind(this);
  }

  handleUpdateCode(editor, metadata, newCode) {
    pageStore.content = newCode;
  }

  render() {
    // TODO Add suppport switchable editor themes.
    const slug = pageStore.slug !== '' ? pageStore.slug : siteStore.landingPage;

    return (
      <form
        style={{
          display: 'grid',
          gridTemplateColumns: '1fr 4fr',
          gridTemplateRows: '1fr 0.5fr 0.5fr 1fr 4fr 0.5fr',
          marginTop: '10px',
        }}
      >
        <h2 style={{ gridColumn: 'span 2' }}>Page Editor</h2>
        <label
          htmlFor='title'
          style={{
            textAlign: 'right',
            verticalAlign: 'middle',
            marginRight: '10px'
          }}
        >
          Title
        </label>
        <input
          id='title'
          type='text'
          placeholder='Name'
          value={ pageStore.title } />
        <label
          htmlFor='slug'
          style={{
            textAlign: 'right',
            verticalAlign: 'middle',
            marginRight: '10px',
            marginTop: '10px',
          }}
        >
          Slug
        </label>
        <input
          id='slug'
          style={{ marginTop: '10px'}}
          type='text'
          placeholder='Slug'
          value={ slug } />
        <h3
          style={{
            gridColumn: 'span 2',
            marginTop: '10px'
          }}
        >
          Content
        </h3>
        <div
          style={{
            gridColumn: 'span 2',
          }}
        >
          <CodeMirror
            autoFocus={ false }
            autoCursor={ false }
            value={ pageStore.content }
            onChange={ this.handleUpdateCode }
            options={{
              mode: 'markdown',
              theme: 'monokai',
              lineWrapping: true,
              lineNumbers: true,
            }} />
        </div>
      </form>
    );
  }
}
