import React, {Component} from 'react';
import {getSetting, SAVE_GLOBAL_VARS, SAVED_SESSIONS, setSetting} from '../../../shared/settings';
import {BUTTON, ROW} from '../../../../gui-common/components/AntdTypes';
import SessionStyles from './Session.css';
import {Button, Checkbox, Col, Form, Input, Modal, Row, Select, Tooltip} from 'antd';
import CapabilityControl from './CapabilityControl';
import {DeleteOutlined, PlusOutlined} from '@ant-design/icons';
import FormattedCaps from './FormattedCaps';
import {showGlobalVarsModal} from '../../actions/Session';
const {Item: FormItem} = Form;
const whitespaces = /^\s|\s$/;

function whitespaceMsg (value) {
  const leadingSpace = /^\s/.test(value);
  const trailingSpace = /\s$/.test(value);

  if (leadingSpace && trailingSpace) {return 'Contains Leading & Trailing Whitespace';}
  if (leadingSpace) {return 'Contains Leading Whitespace';}
  if (trailingSpace) {return 'Contains Trailing Whitespace';}
}
export default class GlobalVarsEditor extends Component {

  constructor (props) {
    super(props);
    this.state = {
      globalVars: []
    };
    this.setCapabilityParam = this.setCapabilityParam.bind(this);
    this.handleSetType = this.handleSetType.bind(this);
    this.removeCapability = this.removeCapability.bind(this);
    this.addCapability = this.addCapability.bind(this);
    this.saveCapability = this.saveCapability.bind(this);
  }

  componentDidMount () {

    (async () => {
      const globalVars = await getSetting(SAVE_GLOBAL_VARS);
      this.setState({globalVars});
    })();
  }

  setCapabilityParam(index, name, value) {

    const {globalVars} = this.state;
    globalVars[index][name] = value;
    this.setState({globalVars});
  }

  handleSetType (index, type) {
    const {globalVars} = this.state;
    this.setCapabilityParam(index, 'type', type);

    // Translate the current value to the new type
    let translatedValue = globalVars[index].value;
    switch (type) {
      case 'text':
        translatedValue = translatedValue + '';
        break;
      case 'number':
        translatedValue = parseInt(translatedValue, 10) || 0;
        break;
      default:
        break;
    }
    this.setCapabilityParam(index, 'value', translatedValue);
  }

  removeCapability (index) {
    const {globalVars} = this.state;
    const newGlobalVars = globalVars.filter((cap, index_) => index_ !== index);
    this.setState({globalVars: newGlobalVars});
  }

  addCapability () {
    const {globalVars} = this.state;
    globalVars.push({type: 'text'});
    this.setState({globalVars});
  }

  saveCapability () {
    const {showGlobalVarsModal} = this.props
    showGlobalVarsModal(false);
    (async () => {
      const {globalVars} = this.state;
      await setSetting(SAVE_GLOBAL_VARS, globalVars);
    })();
  }

  render () {
    const {t, isGlobalVarShow , showGlobalVarsModal} = this.props
    const {globalVars} = this.state;
    const footer = [<Button key="save" type={BUTTON.PRIMARY} onClick={this.saveCapability}>{t('Save')}</Button>];
    return <Modal key="modal"
                  className={SessionStyles.cloudProviderModal}
                  onCancel={ () => {
                    showGlobalVarsModal(false)
                  }}
                  footer={footer}
                  visible={isGlobalVarShow}
                  title={t('Add Global Vars')}>
      <div style={{height: '400px'}}>
        <Row type={ROW.FLEX} align="top" justify="center" className={SessionStyles.capsFormRow}>
          <Col order={1} span={24} className={SessionStyles.capsFormCol}>
            <Form
              className={SessionStyles.newSessionForm}
            >

              {globalVars.map((cap, index) => <Row gutter={8} key={index}>
                <Col span={7}>
                  <FormItem>
                    <Tooltip title={whitespaceMsg(cap.name)} visible={whitespaces.test(cap.name)}>
                      <Input id={`globalVarsName_${index}`} placeholder={t('Name')}
                             value={cap.name} onChange={(e) => this.setCapabilityParam(index, 'name', e.target.value)}
                             className={SessionStyles.capsBoxFont}
                      />
                    </Tooltip>
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem>
                    <Select onChange={(val) => this.handleSetType(index, val)} defaultValue={cap.type}>
                      <Option value='text'>{t('text')}</Option>
                      <Option value='number'>{t('number')}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span={7}>
                  <FormItem>
                    <Tooltip title={whitespaceMsg(cap.value)} visible={whitespaces.test(cap.value)}>
                      <Input id={`globalVarsValue_${index}`} placeholder={t('value')}
                             value={cap.value} onChange={(e) => this.setCapabilityParam(index, 'value', e.target.value)}
                             className={SessionStyles.capsBoxFont}
                      />
                    </Tooltip>
                  </FormItem>
                </Col>
                <Col span={2}>
                  <div className={SessionStyles.btnDeleteCap}>
                    <FormItem>
                      <Button icon={<DeleteOutlined/>}
                              onClick={() => this.removeCapability(index)}/>
                    </FormItem>
                  </div>
                </Col>
              </Row>)}
              <Row>
                <Col span={22}>
                  <FormItem>
                    {t(' add your global vars')}
                  </FormItem>
                </Col>
                <Col span={2}>
                  <FormItem>
                    <Button
                      id='btnAddDesiredCapability'
                      icon={<PlusOutlined/>}
                      onClick={this.addCapability}
                      className={SessionStyles['add-desired-capability-button']} />
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Col>
        </Row>
      </div>

      </Modal>;
  }

}
