import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomErrorStateMatcher } from '@app/_helpers';
import { AuthService } from '@app/_services';
import { Router } from '@angular/router';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AuthComponent implements OnInit {
  keyForm: FormGroup;
  submitted: boolean = false;
  loading: boolean = false;
  matcher: CustomErrorStateMatcher = new CustomErrorStateMatcher();

  constructor(
    private authService: AuthService,
    private formBuilder: FormBuilder,
    private router: Router
  ) {}

  async ngOnInit(): Promise<void> {
    this.keyForm = this.formBuilder.group({
      key: ['', Validators.required],
    });
    await this.authService.init();
    // if (this.authService.privateKey !== undefined) {
    //   const setKey = await this.authService.setKey(this.authService.privateKey);
    //   }
    // }
  }

  get keyFormStub(): any {
    return this.keyForm.controls;
  }

  async onSubmit(): Promise<void> {
    this.submitted = true;

    if (this.keyForm.invalid) {
      return;
    }

    this.loading = true;
    await this.authService.setKey(this.keyFormStub.key.value);
    this.loading = false;
  }

  login(): void {
    // TODO check if we have privatekey
    // Send us to home if we have a private key
    // talk to meta somehow
    // in the error interceptor if 401/403 handle it
    // if 200 go /home
    if (this.authService.getPrivateKey()) {
      this.router.navigate(['/home']);
    }
  }

  switchWindows(): void {
    this.authService.sessionToken = undefined;
    const divOne: HTMLElement = document.getElementById('one');
    const divTwo: HTMLElement = document.getElementById('two');
    this.toggleDisplay(divOne);
    this.toggleDisplay(divTwo);
  }

  toggleDisplay(element: any): void {
    const style: string = window.getComputedStyle(element).display;
    if (style === 'block') {
      element.style.display = 'none';
    } else {
      element.style.display = 'block';
    }
  }
}
