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 {

  constructor(public router: Router, private problemService: ProblemService) { }
  id: number;
  problem: Problem;

  ngOnInit(): void {
    this.id = parseInt(this.router.url.split('/')[2]);
    this.getProblem();
    var editor_area = document.getElementById('editor');
    var editor = CodeMirror.fromTextArea(editor_area, {
      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",
    });

    var active_lang = 0;
    var langs = ["C++", "Python", "Java"];
    var langs_mime = ["text/x-c++src", "text/x-python", "text/x-java"];

    var problem = this.problem;

    document.getElementById('toggle-lang').onclick = function () {
      let th = this as HTMLDivElement;
      active_lang = (active_lang + 1) % 3;
      th.innerHTML = langs[active_lang];
      editor.setValue(problem.default_code[active_lang]);
      editor.setOption("mode", langs_mime[active_lang]);
    }

  }

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

}
