import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'
import { map, first } from 'rxjs/operators'

import { ActionService } from '../action.service'
import { MessageService } from '../message.service'

import { AuthService } from '../services/auth.service'
import { ConfigService } from '../config.service'
import { User } from '../models'
import { DataService, pendingTreeDbName } from '../data.service'

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
  user: User
  pendingTreeDbName = pendingTreeDbName
  pendingTreesCount: number

  constructor(
    public actionService: ActionService,
    public messageService: MessageService,
    public authService: AuthService,
    public cdr: ChangeDetectorRef,
    public configService: ConfigService,
    public dataService: DataService,
  ) {}

  ngOnInit(): void {
    this.updatePendingTrees()
    this.dataService.updatePendingTrees$.subscribe(
      () => this.updatePendingTrees()
    )
   }

  updatePlantekeyData() {
    this.actionService.updatePlantekeyData().subscribe({
      complete: () => {
        this.messageService.message.next('Update server data successful')
      },
      error: error => {
        console.error(error)
        this.messageService.message.next(`Update failed: ${error.statusText}`)
      }
    })
  }

  updatePlantekeyImages() {
    this.actionService.updatePlantekeyImages().subscribe({
      complete: () => {
        this.messageService.message.next('Update server images successful')
      },
      error: error => {
        console.error(error)
        this.messageService.message.next(`Update failed: ${error.statusText}`)
      }
    })
  }

  makeAttachmentsTarFile() {
    this.actionService.makeAttachmentsTarFile().subscribe({
      complete: () => {
        this.messageService.message.next('Tar file creation successful')
      },
      error: error => {
        console.error(error)
        this.messageService.message.next(`Update failed: ${error.statusText}`)
      }
    })
  }

  updatePendingTrees() {
    this.dataService.dbService.count(pendingTreeDbName).pipe(first()).pipe(map(
      count => {
        this.pendingTreesCount = count
        this.cdr.markForCheck()
      }
    )).subscribe()
  }
}
