import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IActiveTosResponseModel } from '@fleio-api/core/model/active-tos-response.model';
import { TosAgreementsApiService } from '@fleio-api/core/tos-agreements-api.service';

@Component({
  selector: 'app-terms-of-service-agree-form',
  templateUrl: './terms-of-service-agree-form.component.html',
  styleUrls: ['./terms-of-service-agree-form.component.scss']
})
export class TermsOfServiceAgreeFormComponent extends DetailsFormBase<any> implements OnInit {
  @ViewChild('formErrors') formErrors;
  agreeForm = this.formBuilder.group({
    agree: ['']
  });
  formGroup = this.agreeForm;
  tos: IActiveTosResponseModel;
  translatedContent: string;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    public config: ConfigService,
    private tosApiService: TosAgreementsApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  agree(): Observable<IActionResult> {
    const value = this.agreeForm.value;
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    if (value.agree) {
      this.objectController.loading = true;
      this.tosApiService.agree(
        this.tos.tos_data.agreement_id
      ).subscribe(() => {
        this.notificationService.showMessage($localize`You agreed with terms of service.`);
        this.router.navigateByUrl(this.config.getPanelHomeUrl()).then(() => {
        });
      }, error => {
        this.objectController.loading = false;
        if (error.error) {
          this.setErrors(error.error);
          return of(null);
        } else {
          throw error;
        }
      });
    }
    return of(null);
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.tos = this.objectController.additionalObjects.tos;
      this.translatedContent = $localize`${this.tos.tos_data.content}`;
    }
  }

}
