/* eslint flowtype-errors/show-errors: 0 */
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router';
import hive from '@hiveio/hive-js';

import App from './containers/App';
import AdvancedPage from './containers/AdvancedPage';
import AccountsPage from './containers/AccountsPage';
import DebugPage from './containers/DebugPage';
import PromptOperation from './containers/PromptOperation';
import SettingsPage from './containers/SettingsPage';
import SendPage from './containers/SendPage';
import TransactionsPage from './containers/TransactionsPage';
import WelcomePage from './containers/WelcomePage';
import VestingPage from './containers/VestingPage';
import ConvertPage from './containers/ConvertPage';
import DecryptPrompt from './containers/DecryptPrompt';
import ServerStatus from './containers/ServerStatus';

import * as HiveActions from './actions/hive';

class Routes extends Component {
  isURL(str) {
    const pattern = new RegExp('^(https?:\\/\\/)?' // protocol
      + '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|' // domain name
      + '((\\d{1,3}\\.){3}\\d{1,3}))' // OR ip (v4) address
      + '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' // port and path
      + '(\\?[;&a-z\\d%_.~+=-]*)?' // query string
      + '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
    return pattern.test(str);
  }

  changeNode(url) {
    if (url && this.isURL(url)) {
      // If it's a valid URL, set
      hive.api.setOptions({ url });
      hive.api.getConfig((err, result) => {
        hive.config.set('chain_id', result.HIVE_CHAIN_ID);
        hive.config.set('address_prefix', result.HIVE_ADDRESS_PREFIX);
      });
    } else {
      // Otherwise set to the api.hive.blog node
      hive.api.setOptions({ url: 'https://api.hive.blog' });
    }
    // Force a refresh immediately after change
    this.props.actions.refreshGlobalProps();
  }

  componentWillMount() {
    if (this.props.preferences && this.props.preferences.hived_node) {
      this.changeNode(this.props.preferences.hived_node);
    }
  }

  componentWillReceiveProps(nextProps) {
    const nextNode = nextProps.preferences.hived_node;
    const thisNode = this.props.preferences.hived_node;
    if (nextNode !== thisNode) {
      this.changeNode(nextNode);
    }
  }

  render() {
    const parse = require('url-parse');
    const parsed = parse(window.location.href, true);
    if (parsed && parsed.query && parsed.query.action && parsed.query.action === 'promptOperation') {
      return (
        <App>
          <DecryptPrompt />
          <PromptOperation query={parsed.query} />
        </App>
      );
    }
    return (
      <App>
        {false && <ServerStatus {...this.props} />}
        <DecryptPrompt />
        <Switch>
          <Route
            exact
            path="/"
            render={
              (props) => {
                if (this.props.keys.isUser) {
                  return <TransactionsPage />;
                }
                return <WelcomePage />;
              }
            }
          />
          <Route path="/transactions" component={TransactionsPage} />
          <Route path="/debug" component={DebugPage} />
          <Route path="/send" component={SendPage} />
          <Route path="/convert" {...this.props} component={ConvertPage} />
          <Route path="/vesting" component={VestingPage} />
          <Route path="/accounts" component={AccountsPage} />
          <Route path="/settings" component={SettingsPage} />
          <Route path="/advanced" component={AdvancedPage} />
        </Switch>
      </App>
    );
  }
}

function mapStateToProps(state) {
  return {
    account: state.account,
    keys: state.keys,
    location: state.location,
    preferences: state.preferences,
    router: state.router,
    hive: state.hive,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
      ...HiveActions
    }, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Routes);
