import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Problem} from '../problem';
import {ProblemService} from '../problem.service';
import {File} from '../file';
import {ApiService} from '../api.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;
  files: File[] = [];

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

  ngOnInit(): void {
    this.id = parseInt(this.router.url.split('/')[3], 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, {
      borderBottom: '1px solid #ddf',
      padding: '20px',
      fontFamily: '"Anonymous Pro", monospace',
    });

    let activeLang = 0;
    const langs = ['C++', 'Python', 'Java'];
    const extensions = ['.cpp', '.py', '.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]);
    };

    const filename = this.id.toString(10);
    const username = JSON.parse(this.apiService.getToken()).username;
    for (const ext of extensions) {
      this.files.push({
        id: null,
        username,
        filename,
        language: ext,
        text: ''
      });
    }

  }

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

}
