import React from 'react';
import './DependencyList.css';
import {connect} from 'react-redux';
import * as Constants from '../../constants';
import Dependency from './Dependency/Dependency';
import Box from '../UI/Box/Box';
import {downloadItem} from '../../redux/actions/download_actions';
import {extractFileNameFromURL} from '../../utils';
import {setDismissDependencies} from '../../redux/actions/install_actions';

const mapStateToProps = state => {
  return {
    AllowDismissDependencies: state.relver.AllowDismissDependencies,
    MissingDependencies: state.install.MissingDependencies,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    downloadItem: (name, type, url, isWinFSP) => dispatch(downloadItem(name, type, url, isWinFSP)),
    setDismissDependencies: dismiss => dispatch(setDismissDependencies(dismiss)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(props => {
  const items = props.MissingDependencies.map((k, i)=> {
    return (
      <Dependency key={i}
                  name={k.display}
                  onDownload={()=>props.downloadItem(extractFileNameFromURL(k.download), Constants.INSTALL_TYPES.Dependency, k.download, k.is_winfsp)}/>
    );
  });

  const dismissDisplay = (
    <div style={{float: 'right', margin: 0, paddingRight: '4px', boxSizing: 'border-box', display: 'block'}}>
      <a href={'#'}
         onClick={props.AllowDismissDependencies ? () => props.setDismissDependencies(true) : e => e.preventDefault()}
         style={{cursor: props.AllowDismissDependencies ? 'pointer' : 'no-drop'}}>X</a>
    </div>
  );

  return (
    <Box dxStyle={{width: '300px', height: 'auto', padding: '5px'}}>
      {dismissDisplay}
      <div style={{width: '100%', height: 'auto', paddingBottom: '5px', boxSizing: 'border-box'}}>
        <h1 style={{width: '100%', textAlign: 'center', color: 'var(--text_color_error)'}}>Missing Dependencies</h1>
      </div>
      {items}
    </Box>
  );
});
