/*
 * Copyright (c) 2020 ETSI.  All rights reserved.
 */

import PropTypes from 'prop-types';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import { connect } from 'react-redux';
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { getSorting } from '../../util/table-utils';
import {
  uiSandboxChangeApiDetailedData,
  uiChangeCurrentDialog
} from '../../state/ui';
import {
  DIALOG_DETAILED_DATA,
  DEFAULT_NO_NETWORK_FILE_SELECTED
} from '../../app-constants';

const tableStyles = () => ({
  root: {
    width: '100%'
  },
  table: {
    maxHeight: 500
  },
  tableBody: {
    maxHeight: 500
  },
  tableWrapper: {
    maxHeight: 500,
    overflowX: 'auto',
    overflowY: 'scroll'
  },
  tableHeadCell: {
    paddingLeft: 15,
    paddingRight: 0,
    color: '#FFFFFF',
    'background-color': '#02488d',
    'font-family': 'Rubik',
    'font-size': '0.8rem',
    'font-weight': 500
  },
  tableBodyCell: {
    paddingLeft: 15,
    paddingRight: 0,
    'font-family': 'Rubik'
  },
  tableBodyCellNoWrap: {
    paddingLeft: 15,
    paddingRight: 0,
    'font-family': 'Rubik',
    whiteSpace: 'nowrap'
  }
});

const tableColumnData = [
  {
    id: 'id',
    numeric: false,
    disablePadding: false,
    label: 'ID'
  },
  {
    id: 'respCode',
    numeric: false,
    disablePadding: true,
    label: 'RESP. CODE'
  },
  {
    id: 'direction',
    numeric: false,
    disablePadding: true,
    label: 'TYPE'
  },
  {
    id: 'method',
    numeric: false,
    disablePadding: true,
    label: 'METHOD'
  },
  {
    id: 'endpoint',
    numeric: false,
    disablePadding: false,
    label: 'ENDPOINT'
  },
  {
    id: 'time',
    numeric: false,
    disablePadding: true,
    label: 'TIME'
  }
];

class ApiTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dismissibleOpen: true
    };
    this.classes = props.classes;
  }

  onClick(event, row) {
    this.props.changeDetailedData(row);
    this.props.changeCurrentDialog(DIALOG_DETAILED_DATA);
  }

  mapService(loggerName) {
    switch(loggerName) {
    case 'meep-loc-serv':
      return '013';
    case 'meep-rnis':
      return '012';
    case 'meep-wais':
      return '028';
    default:
      return 'N/A';
    }
  }

  mapDirection(direction) {
    switch(direction) {
    case 'RX':
      return 'Request';
    case 'TX':
      return 'Notification';
    default:
      return 'N/A';
    }
  }

  render() {
    const classes = this.classes;
    var data = null;
    if (this.props.tableData && this.props.networkFileSelected !== DEFAULT_NO_NETWORK_FILE_SELECTED) {
      data = this.props.tableData.values;
    }
    // const data = this.props.table.entries;
    const order = 'desc';
    const orderBy = 'time';

    const maxRows = 9;
    var emptyRows = 0;
    if (!data || !data.length) {
      emptyRows = maxRows;
    } else {
      emptyRows = Math.max(0, maxRows - data.length);
    }

    return (
      <Paper className={classes.root}>
        <div className={classes.tableWrapper}>
          <Table
            className={classes.table}
            aria-labelledby="tableTitle"
            style={{ width: '100%' }}
          >
            <TableHead>
              <TableRow title="View MEC API requests & notifications">
                {tableColumnData.map(column => {
                  return (
                    <TableCell
                      key={column.id}
                      numeric={column.numeric}
                      padding={column.disablePadding ? 'none' : 'default'}
                      sortDirection={
                        orderBy === column.id ? order : false
                      }
                      className={classes.tableHeadCell}
                    >
                      {column.label}
                    </TableCell>
                  );
                }, this)}
              </TableRow>
            </TableHead>
            {emptyRows < maxRows && <TableBody className={classes.tableBody} title="Click to get detailed info">
              {data
                .sort(getSorting(order, orderBy))
                .map((row) => {
                  return (
                    <TableRow
                      hover
                      onClick={event => this.onClick(event, row)}
                      role="checkbox"
                      tabIndex={-1}
                      key={row.time}
                    >
                      <TableCell className={classes.tableBodyCellNoWrap} scope="row">
                        {this.mapService(row.loggerName) + '-' + row.id}
                      </TableCell>
                      <TableCell className={classes.tableBodyCell} padding='none'>
                        {row.respCode}
                      </TableCell>
                      <TableCell className={classes.tableBodyCell} padding='none'>
                        {this.mapDirection(row.direction)}
                      </TableCell>
                      <TableCell className={classes.tableBodyCell} padding='none'>
                        {row.method}
                      </TableCell>
                      <TableCell className={classes.tableBodyCell}>
                        {row.endpoint}
                      </TableCell>
                      <TableCell className={classes.tableBodyCell} padding='none'>
                        {row.time}
                      </TableCell>
                    </TableRow>
                  );
                })
              }
              {emptyRows > 0 && (
                <TableRow style={{ height: 49 * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
            }
            {emptyRows === maxRows && (
              <TableBody className={classes.tableBody}>
                <TableRow style={{ height: 49 * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              </TableBody>
            )}
          </Table>
        </div>
      </Paper>
    );
  }
}

ApiTable.propTypes = {
  classes: PropTypes.object.isRequired
};

const mapStateToProps = state => {
  return {
    order: state.ui.order,
    tableData: state.sbox.apiTable,
    networkFileSelected: state.ui.networkFileSelected
  };
};

const mapDispatchToProps = dispatch => {
  return {
    changeDetailedData: row => dispatch(uiSandboxChangeApiDetailedData(row)),
    changeCurrentDialog: type => dispatch(uiChangeCurrentDialog(type))
  };
};

export default withStyles(tableStyles)(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(ApiTable)
);
