/*
 * 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: 650
  },
  tableBody: {
    maxHeight: 650
  },
  tableWrapper: {
    maxHeight: 650,
    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.classes = props.classes;
  }

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

  mapService(loggerName) {
    //loggerName is a combination of loggerName and mep name
    let prefixes = ['meep-loc-serv', 'meep-rnis', 'meep-wais', 'meep-app-enablement', 'meep-ams'];
    let prefixStd = '';
    var prefix = '';
    for (var i = 0; i < prefixes.length; i++) {
      if (loggerName.startsWith(prefixes[i])) {
        prefix = prefixes[i];
        break;
      }
    }

    switch(prefix) {
    case 'meep-loc-serv':
      prefixStd = '013';
      break;
    case 'meep-rnis':
      prefixStd = '012';
      break;
    case 'meep-wais':
      prefixStd = '028';
      break;
    case 'meep-app-enablement':
      prefixStd = '011';
      break;
    case 'meep-ams':
      prefixStd = '021';
      break;
    default:
      prefixStd = 'N/A';
    }
    return loggerName.replace(prefix, prefixStd);
  }

  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.apiTable && this.props.networkFileSelected !== DEFAULT_NO_NETWORK_FILE_SELECTED) {
      data = this.props.apiTable.values;
    }
    // const data = this.props.table.entries;
    const order = 'desc';
    const orderBy = 'time';

    const maxRows = 12;
    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,
    apiTable: state.sbox.apiTable.data,
    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)
);
