import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { basename } from 'path';

import { clearColl } from 'redux/modules/collection';

import './style.scss';


class Indexing extends Component {

  static contextTypes = {
    router: PropTypes.object
  };

  static propTypes = {
    host: PropTypes.string,
    dispatch: PropTypes.func
  }

  constructor(props) {
    super(props);

    this.interval = null;
    this.state = {
      data: null
    };
  }

  componentWillMount() {
    this.props.dispatch(clearColl());
  }

  componentDidMount() {
    const { host } = this.props;
    const reqUrl = `${host}_upload/@INIT?user=local`;
    console.log(reqUrl);

    this.interval = setInterval(() => {
      fetch(reqUrl).then(res => res.json())
                   .then(this.displayProgress)
                   .catch(err => console.log(err));
    }, 250);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  displayProgress = (data) => {
    if (data.done && data.done === '1') {
      clearInterval(this.interval);
      this.context.router.push('/local/collection');
    } else {
      this.setState({
        file: basename(data.filename),
        progress: (((data.size / data.total_size) * 100) + 0.5) | 0
      });
    }
  }

  render() {
    const { file, progress } = this.state;
    return (
      <div id="indexingContainer">
        <div className="progress-window">
          <h1>Please wait while the archive is indexed...</h1>
          <h3>Now Indexing: { file }</h3>
          <div className="progress-bar">
            <div className="progress" style={{ width: `${progress || 0}%` }} />
            <div className="progress-readout">{ `${progress || 0}%` }</div>
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = ({ app }) => {
  return {
    host: app.getIn(['appSettings', 'host'])
  };
};

export default connect(mapStateToProps)(Indexing);

@@ -142,16 +142,67 @@
  'path';
+%0Aimport %7B createSearchAction %7D from 'redux-search';
 %0A%0Aimport
@@ -436,16 +436,53 @@
 ispatch:
+ PropTypes.func,%0A    searchBookmarks:
  PropTyp
@@ -634,24 +634,62 @@
 ount() %7B%0A   
+ const %7B dispatch, searchBookmarks %7D =
  this.props.
@@ -687,17 +687,22 @@
 is.props
-.
+;%0A    
 dispatch
@@ -715,16 +715,72 @@
 Coll());
+%0A%0A    // clear search%0A    dispatch(searchBookmarks(''));
 %0A  %7D%0A%0A  
@@ -2118,16 +2118,145 @@
  %7D;%0A%7D;%0A%0A
+const mapDispatchToProps = (dispatch) =%3E %7B%0A  return %7B%0A    searchBookmarks: createSearchAction('bookmarks'),%0A    dispatch%0A  %7D;%0A%7D%0A%0A
 export d
@@ -2270,16 +2270,19 @@
 connect(
+%0A  
 mapState
@@ -2288,16 +2288,39 @@
 eToProps
+,%0A  mapDispatchToProps%0A
 )(Indexi

Clear search when opening new warcs