import { AfterViewInit, Component, Inject, OnInit, Renderer2, ViewChildren, QueryList, OnDestroy } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { AbstractControl, FormBuilder, FormGroup, NgForm } from '@angular/forms';
import { NouisliderComponent } from 'ng2-nouislider';
import { has as _has } from 'lodash/object';
import { KnokService } from '../../shared';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'knk-feedback-ended',
  styleUrls: ['knk-feedback-ended.component.scss'],
  templateUrl: 'knk-feedback-ended.component.pug'
})
export class KnkFeedbackEndedComponent implements OnInit, OnDestroy {
  lang: string;
  feedbackForm: FormGroup;
  knokId: number = -1;

  private ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(public dialogRef: MatDialogRef<any>,
              @Inject(MAT_DIALOG_DATA) private data: any,
              private renderer: Renderer2,
              private translateService: TranslateService,
              private knokService: KnokService,
              private fb: FormBuilder) {
    this.knokId = +data.knokId;
  }

  ngOnInit(): void {
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;

    this.feedbackForm = this.fb.group({
      knokId: this.fb.control(String(this.knokId)),
      knokBenefit: this.fb.control('1'),
      comment: this.fb.control('')
    });
    this.feedbackForm.updateValueAndValidity({emitEvent: false});
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  onSubmit(form: FormGroup): void {
    if (this.feedbackForm.valid) {
      this.knokService.addEndedKnokFeedback(this.feedbackForm.value).subscribe((result: any) => {
        if (_has(result, ['value']) && !!result.value) {
          Observable.timer(1000).takeLast(1).subscribe((): void => {
            this.feedbackForm.reset({
              knokId: String(this.knokId),
              knokBenefit: '1',
              comment: ''
            }, {emitEvent: true});
            this.feedbackForm.updateValueAndValidity({emitEvent: false});

            if (_has(this.data, ['markFeedback']) && typeof this.data.markFeedback === 'function') {
              this.data.markFeedback();
            }
            this.close();
          });
        }
      });
    }
  }

  close(): void {
    this.dialogRef.close(false);
  }
}
