import { RendererApi } from '../common/rendererApi';
import * as impl from './impl';

// DOMの取得
function throwError(msg: string): never {
  throw new Error(msg);
}
const consoleDom = document.getElementById('console') ?? throwError('console Not Found');
const runDom = <HTMLInputElement>document.getElementById('run') ?? throwError('Run Button Not Found');

function escapeHTML(text: string): string {
  const map:{[key: string]: string} = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
  };
  return text.replace(/[<>&]/g, x => map[x]!);
}
// APIの実装
export const api: RendererApi = {
  cmd(c: string, args?: string[]): void {
    let text = c;
    if (args) {
      for (const a of args) {
        text += ' ' + a;
      }
    }
    consoleDom.innerHTML += `<p class='command'>${escapeHTML(text)}</p>`;
  },

  writeLine(text: string): void {
    consoleDom.innerHTML += `<p class='stdout'>${escapeHTML(text)}</p>`;
  },
  writeLineErr(text: string): void {
    consoleDom.innerHTML += `<p class='stderr'>${escapeHTML(text)}</p>`;
  },
  err(text: string): void {
    consoleDom.innerHTML += `<p class='error'>${escapeHTML(text)}</p>`;
  },
  log(text: string): void {
    consoleDom.innerHTML += `<p class='log'>${escapeHTML(text)}</p>`;
  }
};
app.register(api);

// イベントハンドラ
runDom.addEventListener('click', async () => {
  if (runDom.disabled) return;
  runDom.disabled = true;
  try {
    await impl.runAction(api, app.main, app.os);
  } finally {
    runDom.disabled = false;
  }
});
