import {
  CategorySearch,
  DateRange,
  MultiList,
  ReactiveBase,
  ReactiveList,
  ResultCard,
} from '@appbaseio/reactivesearch';
import moment from 'moment';
import React, { Component } from 'react';
import { Col, Grid, Label, Row } from 'react-bootstrap';
import { connect } from 'react-redux';
import { setBreadCrumbs } from '../actions/breadcrumbs';
import { getFileByEventId } from '../api/icat/icatPlus';
import ICATPLUS from '../config/icat/icatPlus';
import TECHNIQUES from '../config/techniques/techniques';
import { stringifyBytesSize } from '../helpers';
import { INVESTIGATION_DATE_FORMAT } from '../constants';

const { ResultCardsWrapper } = ReactiveList;

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.renderDataset = this.renderDataset.bind(this);
  }
  componentDidMount() {
    this.props.setBreadCrumbs([{ name: 'Search' }]);
  }
  getTechniqueColor(definition) {
    if (definition && TECHNIQUES) {
      const technique = TECHNIQUES.find(
        (technique) => technique.shortname === definition
      );
      if (technique) {
        return technique.color;
      }
    }
    return 'white';
  }
  getDatasetImageURL(data) {
    /**Getting the image */
    let url = null;
    if (data.ResourcesGallery) {
      const images = data.ResourcesGallery.split(' ');
      if (images) {
        if (images.length > 0) {
          url = getFileByEventId(
            this.props.user.sessionId,
            data.investigationId,
            images[0]
          );
        }
      }
    }
    return url;
  }
  getTitle(data) {
    const styleTechnique = {
      backgroundColor: this.getTechniqueColor(data.definition),
      fontSize: 10,
    };
    const redirect = `/investigation/${data.investigationId}/datasets`;
    return (
      <div>
        <Grid fluid>
          <Row>
            <Col sm={4}>
              <Label style={styleTechnique}> {data.definition} </Label>
            </Col>
            <Col sm={4} />
            <Col sm={4} style={{ fontSize: 12 }}>
              <Label bsStyle="primary"> DATASET </Label>
            </Col>
          </Row>
          <Row style={{ marginTop: 10 }}>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Name
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              <a href={redirect}>{data.name}</a>
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Sample
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.sampleName}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Proposal
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.investigationName}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Date
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {moment(data.startDate).format(INVESTIGATION_DATE_FORMAT)}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Beamline
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.investigationVisitId}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Files
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.fileCount}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Volume
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {stringifyBytesSize(data.volume)}
            </Col>
          </Row>
        </Grid>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
      </div>
    );
  }

  getFullTitle(data) {
    const styleTechnique = {
      backgroundColor: this.getTechniqueColor(data.definition),
      fontSize: 10,
    };

    const redirect = `/investigation/${data.investigationId}/datasets`;
    return (
      <div>
        <Grid fluid>
          <Row>
            <Col sm={4}>
              <Label style={styleTechnique}> {data.definition} </Label>
            </Col>
            <Col sm={4} />
            <Col sm={4} style={{ fontSize: 12 }}>
              <Label bsStyle="primary"> DATASET </Label>
            </Col>
          </Row>

          <Row style={{ marginTop: 10 }}>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Name
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              <a href={redirect}>{data.name}</a>
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Sample
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.sampleName}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Proposal
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.investigationName}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Date
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {moment(data.startDate).format(INVESTIGATION_DATE_FORMAT)}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Beamline
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.investigationVisitId}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Files
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.fileCount}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Volume
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {stringifyBytesSize(data.volume)}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Mode
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentSource_mode}
            </Col>
          </Row>

          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Type
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentMonochromatorCrystal_type}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Reflection
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentMonochromatorCrystal_reflection}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Usage
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentMonochromatorCrystal_usage}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Energy
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentMonochromator_energy}
            </Col>
          </Row>
          <Row>
            <Col
              sm={3}
              style={{ textAlign: 'left', color: 'gray', fontSize: 11 }}
            >
              Wavelength
            </Col>
            <Col sm={9} style={{ textAlign: 'left', fontSize: 11 }}>
              {data.InstrumentMonochromator_wavelength}
            </Col>
          </Row>
        </Grid>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
      </div>
    );
  }

  getDescription(data) {
    const image = this.getDatasetImageURL(data);
    const redirect = `/investigation/${data.investigationId}/datasets`;
    return (
      <div
        style={{ marginTop: 15 }}
        className="flex column justify-space-between text-center"
      >
        <div>
          <div>
            <span className="authors-list">
              <a href={redirect}>{data.investigationSummary}</a>
            </span>
            <img alt="dataset" src={image} />
          </div>
          <br />
        </div>
      </div>
    );
  }

  renderDataset(data) {
    const image = this.getDatasetImageURL(data);
    if (image) {
      return {
        title: this.getTitle(data),
        image,
        description: this.getDescription(data),
      };
    }
    return {
      title: this.getFullTitle(data),
      description: this.getDescription(data),
    };
  }

  render() {
    const url = `${ICATPLUS.server}/elasticsearch/${this.props.user.sessionId}/`;
    return (
      <div className="app__inner">
        <ReactiveBase app="datasets" url={url} themePreset="light">
          <Grid fluid>
            <Row>
              <Col sm={2} />
              <Col xs={10}>
                <CategorySearch
                  componentId="searchbox"
                  dataField={[
                    'investigationName',
                    'investigationSummary',
                    'name',
                    'definition',
                    'sampleName',
                    'scanType',
                  ]}
                  categoryField="investigationName.keyword"
                  queryFormat="or"
                  placeholder="Search by dataset name, sample name or investigation title"
                />
              </Col>
            </Row>
            <Row>
              <Col sm={2}>
                <br />
                <DateRange
                  componentId="DateSensor"
                  dataField="startDate"
                  title="Filter by date"
                />
                <br />

                <MultiList
                  componentId="BeamlineSensor"
                  dataField="investigationVisitId.keyword"
                  title="Beamlines"
                  react={{
                    and: ['DateSensor', 'DefinitionSensor'],
                  }}
                />
                <br />
                <MultiList
                  componentId="DefinitionSensor"
                  dataField="definition.keyword"
                  title="Technique"
                  react={{
                    and: ['DateSensor', 'BeamlineSensor'],
                  }}
                />
              </Col>
              <Col sm={10}>
                <ReactiveList
                  componentId="result"
                  dataField="name"
                  title="Results"
                  from={0}
                  size={25}
                  paginationAt="top"
                  pagination
                  react={{
                    and: [
                      'searchbox',
                      'DateSensor',
                      'BeamlineSensor',
                      'DefinitionSensor',
                    ],
                  }}
                  style={{
                    width: '60%',
                    textAlign: 'center',
                  }}
                  render={({ data }) => (
                    <ResultCardsWrapper>
                      {data.map((item) => (
                        <ResultCard key={item._id}>
                          <ResultCard.Title>
                            {this.getDescription(item)}
                          </ResultCard.Title>
                          <ResultCard.Description>
                            {this.renderDataset(item).title}
                          </ResultCard.Description>
                        </ResultCard>
                      ))}
                    </ResultCardsWrapper>
                  )}
                />
              </Col>
            </Row>
          </Grid>
        </ReactiveBase>
      </div>
    );
  }
}

/*

 <ResultCard
                        componentId="result"
                        title="Results"
                        dataField="investigationName"
                        from={0}
                        size={20}
                        paginationAt="top"
                        //pagination={false}
                        stream
                        showResultStats
                        react={{
                            //and: ["SingleDropdownListUsage", "RangeSliderSensorWavelength", "searchbox", "DateSensor", "BeamlineSensor", "DefinitionSensor", "RangeSliderSensor", "SingleDropdownListReflection"]
                            //and: ["searchbox", "DateSensor", "BeamlineSensor", "DefinitionSensor"]
                            //and: ["searchbox", "DateSensor", "BeamlineSensor", "DefinitionSensor", "SingleDropdownListUsage", "SingleDropdownListType", "SingleDropdownListReflection", "RangeSliderSensorEnergy", "RangeSliderSensorWavelength"]
                            and: ["searchbox", "DateSensor", "BeamlineSensor", "DefinitionSensor"]
                        }}
                        onData={(res) => {
                            return this.renderDataset(res);
                        }}
                    />




          */

function mapStateToProps(state) {
  return {
    user: state.user,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    setBreadCrumbs: (breadcrumbs) => dispatch(setBreadCrumbs(breadcrumbs)),
  };
}

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