import {Component, OnInit} from '@angular/core';
import {ProblemService} from '../problem.service';
import { ApiService } from '../api.service';
import {Problem} from '../problem';
import { User } from '../user';
import { Question } from '../question';
import { QuestionService } from '../question.service';

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

  user: User;
  problems: Problem[];
  questiontoPost: Question = {
    title: "",
    username: "",
    statement: "",
    tc1_inp: "",
    tc1_out: "",
    tc2_inp: "",
    tc2_out: "",
    start_time: "",
    end_time: ""
  };
  questions: any[];

  constructor(private dataService: ApiService,
    private problemService: ProblemService,
    private questionService: QuestionService) {
  }

  ngOnInit(): void {
    this.user = JSON.parse(this.dataService.getToken());
    this.questiontoPost.username = this.user.username;
    this.getProblems();
    // this.questionService.getQues()
    //   .subscribe(questions => this.questions = questions);
    
    // console.log(this.questions);
  }

  getProblems(): void {
    this.problemService.getProblems()
      .subscribe(problems => this.problems = problems);
  }

  openForm(): void {
    document.getElementById("popupForm").style.display = "block";
  }
  
  closeForm(): void {
    document.getElementById("popupForm").style.display = "none";
  }

  resetForm(): void {
    this.questiontoPost = {
      title: "",
      username: this.user.username,
      statement: "",
      tc1_inp: "",
      tc1_out: "",
      tc2_inp: "",
      tc2_out: "",
      start_time: "",
      end_time: ""
    };
  }

  submitForm() {
    this.questionService.uploadQues(this.questiontoPost).subscribe(
      (event: any) => {
        if (typeof (event) === 'object') {
          this.questiontoPost = null;
          (document.getElementById('quesform') as HTMLInputElement).value = '';
        }
      }
    );
    this.resetForm();
    this.closeForm();
  }
}
