import Detector from "./Detector.js";
import compromise from 'fr-compromise';
import { cleanMessageContent } from "../utils/strings.js";

/*if the beginning of the sentence (before trigger) is less than 7 words then drop
otherwise copy the sentence and adjust
exemple : on mange quoi ce midi ? on mange feur ce midi

does not conjugate

cut to "ça" or "ca" if used 
exemple : c'est quoi ce truc ? c'est feur ce truc
*/

const suffixes = [
  ', mon gars',
  ', mec',
  ", je crois",
  ...Array(10).fill('')
];

export default class SuffixPrefixDetector extends Detector {
  async createSpecificReply(message) {
    const reference = await message.fetchReference().catch(() => null);
    // check if it's a reply to the bot
    const isSelfTarget = (reference && reference.author.id === message.client.user?.id) ?? false;

    const compromiseMatch = compromise(cleanMessageContent(message).toLowerCase()).match(`[<prefix>(!quoi){0,2} (#Verb|faire)? #Preposition?] quoi [<suffix2prefix>#Verb]? [<suffix>(#Determiner !quoi|!quoi)?]?$`);

    if (compromiseMatch == null || compromiseMatch.length === 0) {
      return null;
    }

    return this.conjugateResponse(compromiseMatch, isSelfTarget);
  }

  conjugateResponse(compromiseMatch, isSelfTarget = false) {
    const parsed = compromiseMatch.json();
    const result = parsed[0];

    let replyPrefix = trimPrefix(compromiseMatch.groups('prefix')?.text().trim() ?? '');
    const numberOfWordsInPrefix = replyPrefix.split(' ').length;
    if (numberOfWordsInPrefix > 7) {
      return null; // Too long, pass to next detector
    }
    const replysuffixToPrefix = compromiseMatch.groups('suffix2prefix')?.text().trim() ?? '';
    const replySuffix = compromiseMatch.groups('suffix')?.text().trim() ?? '';

    if (result == null) {
      return '';
    }

    return (`${replyPrefix} ${replysuffixToPrefix} feur ${replySuffix.length > 0 ? ` ${replySuffix}` : ''}${suffixes[Math.floor(Math.random() * suffixes.length)]}`).trim().replaceAll('  ', ' ').replace(' ,', ',');
  }
}

function trimPrefix(prefix) {
  return (prefix
    .split(/(?=(?:ç|c)a)/).at(-1) ?? '')
    .trim();
}