import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Problem} from '../problem';
import {ProblemService} from '../problem.service';

declare const CodeMirror: any;

@Component({
  selector: 'app-arena',
  templateUrl: './arena.component.html',
  styleUrls: ['./arena.component.scss']
})
export class ArenaComponent implements OnInit {

  id: number;
  problem: Problem;

  constructor(public router: Router, private problemService: ProblemService) {
  }

  ngOnInit(): void {
    this.id = parseInt(this.router.url.split('/')[2], 10);
    this.getProblem();
    const editorArea = document.getElementById('editor');
    const editor = CodeMirror.fromTextArea(editorArea as HTMLTextAreaElement, {
      lineNumbers: true,
      theme: 'material-ocean',
      mode: 'text/x-c++src',
      autoCloseBrackets: true,
      matchBrackets: true
    });
    editor.setSize('auto', '70vh');
    editor.setValue(this.problem.default_code[0]);
    Object.assign((document.getElementsByClassName('CodeMirror')[0] as HTMLTextAreaElement).style, {
      border: '2px solid #ddf',
      padding: '20px',
      fontFamily: '"Anonymous Pro", monospace',
    });

    let activeLang = 0;
    const langs = ['C++', 'Python', 'Java'];
    const langsMime = ['text/x-c++src', 'text/x-python', 'text/x-java'];

    const problem = this.problem;

    document.getElementById('toggle-lang').onclick = function(): void {
      const th = this as HTMLDivElement;
      activeLang = (activeLang + 1) % 3;
      th.innerHTML = langs[activeLang];
      editor.setValue(problem.default_code[activeLang]);
      editor.setOption('mode', langsMime[activeLang]);
    };

  }

  getProblem(): void {
    this.problemService.getProblems()
      .subscribe(problems => {
        this.problem = problems.find(i => i.id === this.id);
      });
  }

}
