import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'
import { Location } from "@angular/common"
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { AuthService } from '../services/auth.service'
import { ConfigService } from '../config.service'
import { DataService } from '../data.service'
import { DefaultService } from '../openapi/services.gen'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginComponent implements OnInit {
  form: FormGroup
  msg: String
  constructor(
    private _auth: AuthService,
    public configService: ConfigService,
    private cdr: ChangeDetectorRef,
    public fb: FormBuilder,
    public dataService: DataService,
    private location: Location,
    public apiService: DefaultService,
  ) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    })
  }

  login() {
    this.apiService.loginForAccessTokenTokenPost({
      formData: {
        username: this.form.value['username'],
        password: this.form.value['password'],
      }
    }).subscribe({
      next: (res: any) => {
        if (res.access_token) {
          this._auth.setDataInLocalStorage('token', res.access_token)
          this.msg = undefined
          this.configService.setUserPref('userName', this.form.value['username'])
          this.dataService.syncPendingTrees()
        }
        // After successful login, bootstrap with user's data
        this.configService.bootstrap().subscribe(
          _ => {
            this.location.back()
          }
        )
      },
      error: err => {
        this.msg = err.statusText
        this.cdr.markForCheck()
      }
    })
  }
}