import React from 'react';
import {connect} from 'react-redux';
import * as Constants from '../../../constants';
import Button from '../../UI/Button/Button';
import {formatLinesForDisplay, getChangesForRepertoryVersion} from '../../../utils';
import {
  notifyError,
  notifyInfo
} from '../../../redux/actions/error_actions';
import {installReleaseByVersion} from '../../../redux/actions/install_actions';

const mapDispatchToProps = dispatch => {
  return {
    installReleaseByVersion: (release, version) => dispatch(installReleaseByVersion(release, version)),
    notifyError: msg => dispatch(notifyError(msg)),
    notifyInfo: (title, msg) => dispatch(notifyInfo(title, msg)),
  };
};

export default connect(null, mapDispatchToProps)(({dismiss, release, lastItem, notifyError, notifyInfo, installReleaseByVersion}) => {
  const title = '[' + Constants.RELEASE_TYPES[release.Release] + '] ' + release.Display;
  const installReleaseVersion = () => {
    dismiss();
    installReleaseByVersion(release.Release, release.Version);
  };
  const displayChanges = async () => {
    try {
      const lines = await getChangesForRepertoryVersion(release.VersionString);
      notifyInfo(title, formatLinesForDisplay(lines));
    } catch (e) {
      notifyError(e);
    }
  };

  return (
    <div>
      <h2>{title}</h2>
      <table cellSpacing={0} cellPadding={0} width="97%">
        <tbody>
        <tr style={{height: '4px'}}/>
        <tr>
          <td width="50%">
            <Button buttonStyles={{width: '100%'}} clicked={displayChanges}>Changes</Button>
          </td>
          <td>
            <div style={{width: 'var(--default_spacing)'}}/>
          </td>
          <td width="50%">
            <Button buttonStyles={{width: '100%'}} clicked={installReleaseVersion}>Install</Button>
          </td>
        </tr>
        {lastItem ? null : <tr style={{height: 'var(--default_spacing)'}}/>}
        </tbody>
      </table>
    </div>
  );
});
