import React from 'react';
import {Modal, Grid, Divider} from 'semantic-ui-react';

function randomColor() {
  var colors = [
    'red',
    'orange',
    'yellow',
    'olive',
    'green',
    'teal',
    'blue',
    'violet',
    'purple',
    'pink',
    'brown',
    'grey'
  ];
  colors.sort(function () {
    return 0.5 - Math.random();
  });
  return colors.shift();
}

function ParseTree(props) {
  let {root, ln, lc} = props;
  let ops = {
    "0": "等於",
    "1": "大於",
    "2": "小於",
    "3": "大於等於",
    "4": "小於等於",
    "5": "不等於",
    "8": "AND",
    "9": "OR"
  };

  function GenLN(props) {
    let {data, isRoot} = props;
    return (
      <Grid.Column color={randomColor()} width={isRoot
        ? 16
        : 8}>
        <div>{`ID:${data.jcioclntuid || ''} / Name:${data.lnname || ''} / Action:${data.lnaction || ''}`}</div>
        <Divider horizontal={true}>{ops[data.lnlcop]}</Divider>
        <GenNode ids={[data.lnlcid1, data.lnlcid2]}/>
      </Grid.Column>
    )
  }
  function GenLC(props) {
    let {data} = props;
    return (
      <Grid.Column color={randomColor()} width={8}>
        <div>{`ID:${data.jcioclctuid || ''} / Name:${data.lcname || ''} / Action:${data.lcaction || ''}`}</div>
        <hr/>
        <div>{`${data.lcioid} ${ops[data.lcioop]} ${data.lciovalue}`}</div>
      </Grid.Column>
    )
  }

  function GenNode(props) {
    let {ids} = props;
    let isRoot = ids.length == 1 && ids[0].substr(2) == root
      ? true
      : false;
    let arr = [];
    for (let i in ids) {
      let id = ids[i];
      if (/^ln/.test(id)) {
        let idn = id.match(/^ln(\d+)$/);
        if (!idn || idn.length < 1) 
          continue;
        let num = idn[1];
        for (let j in ln) {
          if (ln[j].jcioclntuid == num) {
            arr.push(<GenLN key={`ln${ln[j].kcioclntuid}`} data={ln[j]} isRoot={isRoot}/>)
          }
        }
      } else if (/^lc/.test(id)) {
        let idn = id.match(/^lc(\d+)$/);
        if (!idn || idn.length < 1) 
          continue;
        let num = idn[1];
        for (let j in lc) {
          if (lc[j].jcioclctuid == num) {
            arr.push(<GenLC key={`lc${lc[j].jcioclctuid}`} data={lc[j]}/>)
          }
        }
      }
    }

    return (
      <Grid>
        {arr.map(t => t)
}
      </Grid>
    )
  }

  return <GenNode ids={[`ln${root}`]}/>
}

const LinkInfo = ({
  i18n,
  open,
  root,
  ln,
  lc,
  onClose
}) => {

  return (
    <Modal size="fullscreen" open={open} onClose={() => {
      onClose()
    }}>
      <Modal.Content>
        <ParseTree root={root} ln={ln} lc={lc}/>
      </Modal.Content>
    </Modal>
  )
}

export default LinkInfo;