import React, {Component} from 'react';
import {Button, Checkbox, Col, Form, Input, Modal, Radio, Row, Select, Tooltip} from 'antd';
import {DeleteOutlined, PlusOutlined, UploadOutlined,} from '@ant-design/icons';
import {ipcRenderer} from '../../polyfills';
import fs from 'fs';
import {BUTTON, ROW} from '../../../../gui-common/components/AntdTypes';
import SessionStyles from './Session.css';
import CapabilityControl from './CapabilityControl';
import FormattedCaps from './FormattedCaps';
import {setTestSuitCapabilityParam} from '../../actions/Inspector';
import {executeScript} 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 ExecuteControl extends Component {

  constructor (props) {
    super(props);
    this.state = {
      filePath: null,
      exeVars: [],
      suiteEnvs: [],
      envVisible: false
    }
    this.sendScript = this.sendScript.bind(this);
    this.receiveRequest = this.receiveRequest.bind(this);
    this.onChange = this.onChange.bind(this);
    this.setTestSuitParams = this.setTestSuitParams.bind(this);
  }

  componentDidMount () {
    ipcRenderer.on('send-script', this.sendScript);
    ipcRenderer.on('receive-request', this.receiveRequest);
    const envParams = {requestName: 'testSuiteEnv'};
    ipcRenderer.send('make-request', JSON.stringify(envParams));
  }

  receiveRequest(evt, args) {

    const {requestName} = JSON.parse(args);

    if (requestName === 'testSuiteEnv') {
      const {convertResponse} = JSON.parse(args);
      this.setState({suiteEnvs: convertResponse});
    }
  }

  sendScript(evt, args) {
    const  {filePath, script} = JSON.parse(args);
    this.setState({filePath: filePath});
    const regex = /\/\/- (.*?) -\/\//;
    const matches = script.match(regex);
    if (matches) {
      const targetString = matches[1];
      const jsonObj = JSON.parse(targetString);
      this.setState({exeVars: jsonObj})
      console.log(targetString);
    } else {
      console.log('No match found.');
    }
  }

  onChange (e) {
    console.log('radio checked', e.target.value);
    const { suiteEnvs, exeVars } = this.state;
    const envElement = suiteEnvs.find((element) => element.key === e.target.value);
    const index = exeVars.findIndex((element) => element.type === 'env');
    if (index !== -1) {
      exeVars[index].key = envElement.key;
      exeVars[index].name = envElement.label;
      this.setState({exeVars})
    }
  };

  componentWillUnmount () {
    ipcRenderer.removeListener('send-script', this.sendScript);
  }

  setTestSuitParams(paramIndex, valueIndex, name, value) {
    const { exeVars } = this.state;
    exeVars[paramIndex].value[valueIndex][name] = value;
    this.setState({exeVars});
  }

  render () {
    const { t, executeScript } = this.props;
    const { exeVars, filePath } = this.state;
    const envElement = exeVars.find((element) => element.type ==='env');
    const envModalValue = envElement === undefined ? null : envElement.key;
    return <Row justify={'center'}>
      <Col span={12}>
        <div style={{ textAlign: 'center' }}>
          <Row gutter={[0,10]} >
            <Col span={24}>
              <div style={{ textAlign: 'center' }}>
                <Button icon={<UploadOutlined />} onClick={ () => {
                  ipcRenderer.send('select-script')
                }}>Select File</Button>
              </div>
            </Col>
            { filePath !== null &&  <Col span={24}>
              <div style={{ textAlign: 'center' }}>
                <p>{filePath.substring(filePath.lastIndexOf("/") + 1)}</p>
              </div>
            </Col>  }
            { envElement !== undefined && <Col span={24}>
              <div style={{ textAlign: 'center' }}>
                <Button key="select" onClick={ () => {
                  this.setState({
                    envVisible: true,
                  })
                } }>{t(envElement.name)} </Button>
              </div>
            </Col>}

            { filePath !== null && <Col span={24}>
              <div style={{ textAlign: 'center' }}>
                <Button key="execute" type={BUTTON.PRIMARY}  onClick={ () => {
                  executeScript(exeVars, filePath);
                } }>{t('execute')} </Button>
              </div>
            </Col>}
          </Row>
        </div>

      </Col>
      <Col span={12}>
          <Row align="top" justify="start" className={SessionStyles.capsFormRow}>
            <Col order={1} span={12} className={SessionStyles.capsFormCol}>
              <Form>
                {
                  exeVars.map((param, paramIndex) => param.type === 'env' ? null : <Row gutter={[0, 5]}>
                    <Col span={24}>
                      <p style={{fontSize: '20px'}}>{param.name}</p>
                    </Col>
                    <Col span={24}>
                      {param.value.map((cap, index) => <Row>
                          <Col span={24} style={{marginBottom: '14px'}}>
                            <Row gutter={8} key={`name_value_${paramIndex}_${index}`} >
                              <Col span={8}>
                                <FormItem>
                                  <Tooltip title={whitespaceMsg(cap.name)} visible={whitespaces.test(cap.name)}>
                                    <Input disabled={true} id={`selectSuitCaps_name_${paramIndex}_${index}`} placeholder={t('Name')}
                                           value={cap.name} className={SessionStyles.capsBoxFont}
                                    />
                                  </Tooltip>
                                </FormItem>
                              </Col>

                              <Col span={16}>
                                <FormItem>
                                  <Tooltip title={whitespaceMsg(cap.value)} visible={whitespaces.test(cap.value)}>
                                    <Input id={`selectSuitCaps_value_${paramIndex}_${index}`} placeholder={t('Value')} value={cap.value} onChange={(e) => this.setTestSuitParams(paramIndex ,index, 'value', e.target.value)}
                                           className={SessionStyles.capsBoxFont} />
                                  </Tooltip>
                                </FormItem>
                              </Col>
                            </Row>

                            <Row gutter={8} key={`type_des_${paramIndex}_${index}`} style={{marginBottom: '8px'}}>
                              <Col span={8}>
                                <FormItem>
                                  <Select onChange={(val) =>  this.setTestSuitParams(paramIndex ,index, 'type', val) } defaultValue={cap.type}>
                                    <Option value='text'>{t('text')}</Option>
                                    <Option value='number'>{t('number')}</Option>
                                    <Option value='variable'>{t('variable')}</Option>
                                  </Select>
                                </FormItem>
                              </Col>

                              <Col span={16}>
                                <FormItem>
                                  <Tooltip title={whitespaceMsg(cap.desc)} visible={whitespaces.test(cap.desc)}>
                                    <Input disabled={true} id={`selectSuitCaps_des_${paramIndex}_${index}`} placeholder={t('description')} value={cap.desc}
                                           className={SessionStyles.capsBoxFont} />
                                  </Tooltip>
                                </FormItem>
                              </Col>
                            </Row>
                          </Col>
                        </Row>
                      )}
                    </Col>
                  </Row>)
                }
              </Form>
            </Col>
          </Row>
      </Col>
      <Modal key="modal"
             visible={this.state.envVisible}
             onCancel={ () => {this.setState({
               envVisible: false,
             })}}
             onOk={ () => {this.setState({
               envVisible: false,
             })}}
             title={t('Select Environment')}>
        <Radio.Group onChange={this.onChange} value={envModalValue}>
          {this.state.suiteEnvs.map((element) => (
            <Radio key={element.key} value={element.key}>
              {element.label}
            </Radio>
          ))}
        </Radio.Group>
      </Modal>
    </Row>
  }
}