import './addChatTextArea.css';
import arrayFrom from '../common/arrayFrom';
import clickThis from '../common/clickThis';
import closestTable from '../common/closestTable';
import contains from '../common/contains';
import createTextArea from '../common/cElement/createTextArea';
import getArrayByClassName from '../common/getArrayByClassName';
import getValue from '../system/getValue';
import insertElement from '../common/insertElement';
import on from '../common/on';
import { pCC } from '../support/layout';
import partial from '../common/partial';

function removeCrlf(fshTxt) {
  // eslint-disable-next-line no-param-reassign
  fshTxt.value = fshTxt.value.replace(/\r\n|\n|\r/g, ' ');
}

const formAttr = (el) => { el.setAttribute('form', 'dochat'); };

function setDoChat(theForm) {
  // eslint-disable-next-line no-param-reassign
  theForm.id = 'dochat';
  arrayFrom(theForm.elements).forEach(formAttr);
}

function rearrangeTable(elements) {
  const theTable = closestTable(elements[5]);
  theTable.rows[0].cells[0].remove();
  insertElement(theTable.insertRow(-1).insertCell(-1), elements[6]);
  theTable.rows[0].cells[0].rowSpan = 2;
}

function keypress(sendBtn, evt) {
  if (evt.key === 'Enter' && !evt.shiftKey) {
    evt.preventDefault();
    clickThis(sendBtn);
  }
}

function makeTextArea() {
  const fshTxt = createTextArea({
    className: 'fshChatTextArea',
    maxLength: 512,
    name: 'msg',
    required: true,
  });
  formAttr(fshTxt);
  return fshTxt;
}

const dont = () => !pCC
  || getArrayByClassName('header', pCC).filter(contains('Posted\xa0By')).length !== 1
  || !getValue('enhanceChatTextEntry');

export default function addChatTextArea() {
  if (dont()) { return; }
  const theForm = document.forms[0];
  setDoChat(theForm);
  rearrangeTable(theForm.elements);
  const fshTxt = makeTextArea();
  on(fshTxt, 'keypress', partial(keypress, theForm.elements[5]));
  theForm.elements[4].replaceWith(fshTxt);
  on(theForm, 'submit', partial(removeCrlf, fshTxt));
}

@@ -655,16 +655,21 @@
 xt.value
+%0A    
 .replace
@@ -688,17 +688,313 @@
 /g, ' ')
-;
+%0A    .replace(/'/g, '%E2%80%99')%0A    // https://stackoverflow.com/a/27449493/1274806%0A    .replace(/(%5E%7C%5Cs)(%22)/g, '$1%E2%80%9C') // replace quotes that start a line or follow spaces%0A    .replace(/%22/g, '%E2%80%9D') // replace quotes that start a line or follow spaces%0A    .replace('%3C', '%EF%BC%9C'); // open angle bracket - sohail94
 %0A%7D%0A%0Acons

replace chat glyphs (#234)