import { Component, OnInit, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core';
import { EmployeeFeedBackService } from '../../../../services/employee/employee-feedback.service';
import { QuestionBase } from '../../../../models/employee.model';
import { FormGroup } from '@angular/forms';
import { Subject } from 'rxjs/Subject';
import { EmployeeHttpService } from '../../../../services/employee/employee-http.service';
import 'rxjs/add/operator/map';
import { environment } from '../../../../../environments/environment.dev';

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

  @Input() reviewerId: string;
  @Input() eventDetailsId: string;
  @Input() useCaseId: string;
  @Output() updateStatus = new EventEmitter();
  private $destroyed = new Subject();
  form: FormGroup;
  questions: QuestionBase<any>[] = [];
  formData = '';
  imagelink = '';
  questionData = {};
  multiChoiceQuestionList = [];
  otherQuestionList = [];
  dataMap = new Map<string, string>();
  dialogData: any;
  isStarRating: boolean;
  passMark = 0;
  payLoad = {
    comments: '',
    eventDtlsId: '',
    feedback: [],
    reviewerId: '',
    score: 0
  };

  constructor(private feedBackService: EmployeeFeedBackService,
    private employeeHttpService: EmployeeHttpService) { }

  ngOnInit() {
    // this.useCaseId = '96';
    this.getReviewQuestions();
    this.imagelink = environment.imageUrl+'/assets/img/employee/newdashboard/';
    this.form = this.feedBackService.toFormGroup(this.questions);
    this.dialogData = { title: 'Review FeedBack Submission', text: 'Are are you want to submit?' };
  }

  getReviewQuestions() {
    console.log('get Review Questions for useCase Id ' + this.useCaseId);
    this.employeeHttpService.getReviewFeedBackQuestions(this.useCaseId).takeUntil(this.$destroyed)
      .subscribe(data => {
        this.questionData = data;
        this.isStarRating = data.rating;
        this.passMark = data.passMarks;
        this.questions = this.feedBackService.getQuestions(this.questionData);
        this.getMultiChoiceQuestions(this.questions);
        this.form = this.feedBackService.toFormGroup(this.questions);
        // console.log('getReviewQuestions API Response', JSON.stringify(this.questionData));
      });
  }

  onSubmit() {
    this.payLoad.feedback = [];
    this.formData = this.form.value;
    // console.log('formData' + JSON.stringify(this.formData));
    this.payLoad.comments = this.formData['overallRating'];
    this.payLoad.score = this.formData['overallRating-feedback'];
    this.payLoad.reviewerId = this.reviewerId;
    this.payLoad.eventDtlsId = this.eventDetailsId;
    this.otherQuestionList.forEach(question => {
      if (question !== 'overallRating') {
        this.payLoad.feedback.push(
          {
            answer: this.formData[question],
            questionId: question,
            rating: this.formData[question + '-feedback'],
          });
      }
    });
    this.multiChoiceQuestionList.forEach(question => {
      this.payLoad.feedback.push(
        {
          answer: this.dataMap.get(question),
          questionId: question,
          rating: this.formData[question + '-feedback'],
        });
    });
    this.calculateScore();
    // console.log ("payLoad" + JSON.stringify(this.payLoad));
  }

  submitEmployeeFeedBack(payLoad) {
    this.employeeHttpService.submitEmployeeFeedBack(payLoad)
      .subscribe(data => {
        console.log('Employee FeedBack submitted Successfully');
        this.updateStatus.emit('Done');
      }, (error) => {
        console.log('Error Encounted in Employee FeedBack Submission');
      });
  }

  captureList(map: Map<string, string>) {
    if (map['isTrusted'] === true) {
    } else {
      map.forEach((value: string, key: string) => {
        this.dataMap.set(key, value);
      });
    }
  }

  getMultiChoiceQuestions(questions) {
    for (const question of questions) {
      if (question.controlType === 'checkbox') {
        this.multiChoiceQuestionList.push(question.key);
      } else {
        this.otherQuestionList.push(question.key);
      }
    }
  }

  gotoUsecase() {
    this.updateStatus.emit('To Do');
  }

  submitForm(event) {
    this.submitEmployeeFeedBack(this.payLoad);
  }

  calculateScore() {
    const score = Number(this.formData['overallRating-feedback']) * 20;
    if (score > this.passMark) {
      this.dialogData['text'] = 'Are you sure want to submit';
    } else {
      this.dialogData['text'] = `Review score(${score}) is less than Pass Mark(${this.passMark}), Are you sure want to submit`;
    }
  }
}
