Newer
Older
Website / src / app / admin / admin.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AccountService } from '../account.service';

interface TimeEntry {
  value: number
  viewValue: string
}

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
  passwordForm: FormGroup
  statusForm: FormGroup
  quoteForm: FormGroup
  public passwordError = false
  public username = ''
  timeOptions: TimeEntry[] = [
    {value: 60, viewValue: '1 Minute'},
    {value: 600, viewValue: '10 Minutes'},
    {value: 3600, viewValue: '1 Hour'},
    {value: 36000, viewValue: '10 Hours'},
    {value: 24 * 3600, viewValue: '1 Day'},
  ]
  defaultTime = '10 Minutes'
  constructor(public account: AccountService, router: Router, private formBuilder: FormBuilder) {
    this.passwordForm = this.formBuilder.group({
      password: ['', Validators.required],
      password_repeat: ['', Validators.required]
    })
    this.statusForm = this.formBuilder.group({
      status: ['', Validators.required],
      time: [null],
    })
    this.quoteForm = this.formBuilder.group({
      quote: ['', Validators.required],
    })
    account.subscribe((username: string) => {
      if (account.username.length == 0) {
        router.navigate(['login'])
      }
      this.username = username
    })
  }

  ngOnInit(): void {
    this.statusForm.get('time')?.setValue(60)
  }

  onPasswordSubmit() {
    if (this.passwordForm.invalid) {
      return
    }
    this.passwordError = this.passwordForm.controls['password'].value !=
                         this.passwordForm.controls['password_repeat'].value
    if (this.passwordError) {
      return
    }
    this.account.changePassword(this.passwordForm.controls['password'].value, () => {
      this.passwordForm.reset()
    }, () => {})
  }

  onStatusSubmit() {
    if (this.statusForm.invalid) {
      return
    }
    this.account.postStatus(this.statusForm.controls['status'].value, this.statusForm.controls['time'].value)
  }

  onQuoteSubmit() {
    if (this.quoteForm.invalid) {
      return
    }
    this.account.updateQuote(this.quoteForm.controls['quote'].value)
  }
}