'use strict';

var qs = x => document.querySelector(x);
var qsa = x => document.querySelectorAll(x);

module.exports = function(communicator) {
    if (!onDiscussionPage()) return;

    let addButtonsMaker = addButtons(communicator);
    let verifyButtonMaker = addVerifyButton(communicator);
    let messages = qs('[role=presentation]>tr>td>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(3)');
    Array.from(messages.querySelectorAll('.kv'))
	.forEach(el => el.addEventListener('click', function() {
	    verifyButtonMaker(this);
	}));
    addButtonsMaker.call(messages);
};

function addButtons(communicator) {
    return function() {
	let erinomeVerify = Array.from(this.querySelectorAll('.erinome-verify'));
	if (erinomeVerify.length !== 0) return;

	Array.from(this.children)
	    .filter(el => el.getAttribute('tabindex') !== null)
	    .forEach(addVerifyButton(communicator));
    };
}

function onDiscussionPage() {
    // Very Specific Gmail Selector
    return qsa('[role=presentation]>tr>td>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(3)>[tabindex]').length > 0;
}

function addVerifyButton(communicator) {
    return function(el) {
	let button = document.createElement('div');
	button.className = 'erinome-verify';
	button.textContent = 'V';
	button.style.background = 'aliceblue';
	button.style.width = '25px';
	button.style.height = '25px';
	button.style.fontSize = '20px';
	button.style.textAlign = 'center';
	button.style.cursor = 'pointer';
	el.querySelector('table>tbody>tr>td:nth-child(2)>div').appendChild(button);
	button.addEventListener('click', verifyEmail(communicator));
    };
}

function findParent(el, nodeName) {
    let tmp = el;
    while (tmp.parentNode.nodeName !== nodeName) {
	tmp = tmp.parentNode;
    }
    return tmp.parentNode;
}

function verifyEmail(communicator) {
    return function() {
	let self = this;
	let email = findParent(this, 'TABLE').parentNode.parentNode.children[5];
	communicator.send({
	    action: 'verify',
	    text: email.innerText
	}).then(function(obj) {
	    self.style.background = obj.result === 0 ? 'green' : 'red';
	}).done();
    };
}

@@ -496,24 +496,96 @@
 unction() %7B%0A
+%09    if (this.querySelectorAll('.erinome-verify').length !== 0) return;%0A
 %09    verifyB
@@ -713,38 +713,11 @@
  %7B%0A%09
-let erinomeVerify = Array.from
+if 
 (thi
@@ -757,29 +757,8 @@
 fy')
-);%0A%09if (erinomeVerify
 .len
@@ -1859,20 +1859,43 @@
 unction(
+e
 ) %7B%0A
+%09e.stopPropagation();%0A
 %09let sel
@@ -1978,16 +1978,56 @@
 ren%5B5%5D;%0A
+%09let text = cleanText(email.innerText);%0A
 %09communi
@@ -2073,28 +2073,17 @@
   text: 
-email.innerT
+t
 ext%0A%09%7D).
@@ -2180,16 +2180,16 @@
 done();%0A
-
     %7D;%0A%7D
@@ -2177,20 +2177,169 @@
 %7D).done();%0A    %7D;%0A%7D%0A
+%0A/**%0A * Email texts on gmail sometimes have ugly chars.%0A * Namely, &nbsp;.%0A */%0Afunction cleanText(text) %7B%0A    return text.replace(/%5Cu00A0/g, ' ');%0A%7D%0A

Verify is now correctly handled.