import React, {Component} from 'react';
import {ipcRenderer} from '../../polyfills';
import {Pagination, Table} from 'antd';

export default class SelectTestSuiteTable extends Component {

  constructor (props) {
    super(props);
    this.state = {
      data: [],
      total: 0,
      currentPage: 0,
      selectedRows: [],
    }

    this.handlePageChange = this.handlePageChange.bind(this);
    this.onSelectChange = this.onSelectChange.bind(this);
    this.requestTestSuiteList = this.requestTestSuiteList.bind(this);
  }

  componentDidMount () {
    ipcRenderer.on('receive-request', this.requestTestSuiteList);
    this.handlePageChange(1);
  }

  requestTestSuiteList (evt, args) {
    const {requestName, convertResponse} = JSON.parse(args);
    if (requestName === 'testSuiteList') {
      this.setState({
        data: convertResponse.rows,
        total: convertResponse.total,
        loading: false,
      });
    }
  }

  componentWillUnmount () {
    ipcRenderer.removeListener('receive-request', this.requestTestSuiteList);
  }

  handlePageChange(page) {
    const { requestTestSuiteList } = this.props;

    if (page !== this.state.currentPage) {
      requestTestSuiteList({skip:(page - 1) * 10});
    }
    this.setState({ currentPage: page });
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    this.setState({selectedRows});
    const {selectTestSuitId} = this.props;
    const selectElement = selectedRows[0];
    selectTestSuitId(selectElement.key, selectElement.label);
  };

  render () {

    const {data} = this.state;
    const columns = [
      {
        title: 'Name',
        dataIndex: 'label',
      },
    ];
    const rowSelection = {
      type: 'radio',
      onChange: this.onSelectChange,
    };

    return <div style={{ height: '100%', overflowY: 'auto' }} >
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        pagination={false}
      />
      <div style={{ marginTop: '20px' }} />

      <Pagination
        total={this.state.total}
        pageSize={10}
        current={this.state.currentPage}
        onChange={this.handlePageChange}
        showSizeChanger={false}
        showQuickJumper={true}
      />
    </div>;
  }

}
