import { getTextFromClipboard } from "./clipboardUtils";
import { convertMathMLToLaTeX } from "./convertMathMLToLaTeX";

export async function getLatexOnCustomPased(
  e: React.KeyboardEvent<HTMLInputElement>,
  shortCut:boolean
): Promise<string | null> {
  if (shortCut) return null;
    e.preventDefault();

    const copyedValue = await getTextFromClipboard();
    const latex = convertMathMLToLaTeX(copyedValue);
    
    return latex;
}

export function getLatexOnCtrlShiftThKeyDown(
  e: React.KeyboardEvent<HTMLInputElement>
): string | null {
  if (!e.ctrlKey || !e.shiftKey || e.code !== "Backquote") return null;

  e.preventDefault(); 

  const selectedText = getSelectedText(e)
  if (!selectedText) return null;

  const latex = convertMathMLToLaTeX(selectedText);
  const result = replaceSelectedTo(e,latex,"$$$");
  
  return result;
}
export function getLatexOnCtrlShiftQkeyDown(
  e: React.KeyboardEvent<HTMLInputElement>
): string | null {
  if (!e.ctrlKey || !e.shiftKey || e.code !== "KeyQ") return null;

  e.preventDefault(); 

  const selectedText = getSelectedText(e)
  if (!selectedText) return null;

  const latex = convertMathMLToLaTeX(selectedText);
  const result = replaceSelectedTo(e,latex,"$$");
  
  return result;
}

export function getSelectedText(e:React.KeyboardEvent<HTMLInputElement>){
        const {start,end,input} = getIndexesOfSelectionValue(e)
        const selectedText = input.value.substring(start, end);
        
        return selectedText
}

export function replaceSelectedTo(e: React.KeyboardEvent<HTMLInputElement>,newValue:string,encabsolation?:string) {
    const {start,end,input} = getIndexesOfSelectionValue(e)

    const before = input.value.substring(0, start);
    const after = input.value.substring(end);
    const trimValue = newValue.trim()
    const result = `${encabsolation} ${trimValue.slice(2,trimValue.length-2)} ${encabsolation}`;

    return result;

}

export function getIndexesOfSelectionValue (e: React.KeyboardEvent<HTMLInputElement>):{start:number,end:number,input:HTMLInputElement} {
      const input = e.target as HTMLInputElement;
    const start = input.selectionStart || 0;
    const end = input.selectionEnd || 0;
    return {start,end,input}
}