/*
Panel containing control elements for managing sites and pages.

@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 FontAwesome from 'react-fontawesome';
import {observer} from 'mobx-observer';

import {UserLogin, UserLogOut} from './UserLoginForm';
import {PageEditor} from './PageEditor';
import {MenuEditor} from './MenuEditor';
import {SiteEditor} from './SiteEditor';
import {SiteFooterEditor} from './SiteFooterEditor';
import {SiteHeaderEditor} from './SiteHeaderEditor';
import {appStatusStore, pageStore, siteStore, userStore} from '../stores';
import {adminStore} from './store';
import {Spacer} from '../layout';


@observer export class ControlPanel extends Component {

  // TODO: Figure out the right size of panel.
  // This the ideal side for an 80 pixel text field is 850px.
  static SIDEBAR_SIZE = '600px';

  // TODO: Make this dynamic.
  static AVAILABLE_BLOCKS = {
    'site': {description: 'Site'},
    'header': {description: 'Site Header'},
    'menu': {description: 'Site Menu'},
    'footer': {description: 'Site Footer'},
    'page': {description: 'Page'},
  };

  constructor() {
    super();
    this.state = {
      selectedBlock: 'none',
    };
    this.handleBlockSelection = this.handleBlockSelection.bind(this);
  }

  handleBlockSelection(event) {
    this.setState({selectedBlock: event.target.value});
  }

  handleResetContent() {
    // TODO: Use the page store instead... (And keep backups...)
    this.setState({displayContent: this.state.originalContent});
  }

  handleSaveContent() {
    // TODO: Add support for saving site + components as well.
    // # TODO Start using proper models for page and json
    let pageContent = {
      slug: pageStore.slug || siteStore.landingPage,
      // TODO: Add support for internally saved title?
      title: pageStore.title,
      content: pageStore.content,
    };
    pageStore.savePage(pageContent);
    siteStore.saveSite();
  }

  render() {
    const panelStyle = {
      backgroundColor: '#222222',
      color: '#ddd',
      padding: '10px',

      display: 'flex',
      flexDirection: 'column',
      flexBasis: ControlPanel.SIDEBAR_SIZE,
      flexShrink: 0,

      width: ControlPanel.SIDEBAR_SIZE,

      transitionProperty: 'all',
      transitionDuration: '0.5s',
      transitionTimingFunction: 'ease-in-out',
    };

    if (!adminStore.showPanel) {
      panelStyle.marginLeft = `-${ControlPanel.SIDEBAR_SIZE}`;
    } else {
      panelStyle.marginLeft = '0';
    }

    const blockMenu = [];
    // TODO: Add in an <optgroup> for the site related blocks.
    Object.entries(ControlPanel.AVAILABLE_BLOCKS)
      .forEach(
        ([key, value]) => {
          blockMenu.push(<option value={ key }>{ value.description }</option>)
        });

    let selectedBlock;
    switch (this.state.selectedBlock) {
      case 'header':
        selectedBlock = (<SiteHeaderEditor/>);
        break;

      case 'footer':
        selectedBlock = (<SiteFooterEditor/>);
        break;

      case 'menu':
        selectedBlock = (<MenuEditor/>);
        break;

      case 'site':
        selectedBlock = (<SiteEditor/>);
        break;

      case 'page':
        selectedBlock = (<PageEditor/>);
        break;

      default:
        selectedBlock = (<div style={{ textAlign: 'center' }}>Select a component to edit...</div>);
    }

    const children = userStore.isUserLoggedIn
      ? (
        <div>
          <UserLogOut />
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              marginTop: '10px',
            }}
          >
            <select
              style={{ width: '100%' }}
              onChange={ this.handleBlockSelection }
              value={ this.state.selectedBlock }
            >
              <option value='none'>Edit component...</option>
              { blockMenu }
            </select>
            <button
              className='btn'
              onClick={ this.handleResetContent }
              style={{ marginLeft: '10px' }}
              type='button'
            >
              <FontAwesome name='undo'/> Revert Changes
            </button>
            <button
              className='btn'
              style={{ marginLeft: '10px' }}
              onClick={ this.handleSaveContent }
              type='button'
            >
              <FontAwesome name='upload'/> Upload to Server
            </button>
          </div>
          <Spacer />
          { selectedBlock }
        </div>
      )
      : (
        <div>
          <UserLogin />
          <Spacer />
        </div>);

    return (
      <div
        style={{...panelStyle}}
      >
        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
          <h1>Rookeries</h1>
          <div style={{textAlign: 'right'}}>version { appStatusStore.version }</div>
        </div>
        {children}
      </div>
    );
  }
}
