import {Component, OnInit} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {Pentest} from '@shared/models/pentest.model';
import {UntilDestroy, untilDestroyed} from '@ngneat/until-destroy';
import { filter, tap} from 'rxjs/operators';
import {NotificationService, PopupType} from '@shared/services/toaster-service/notification.service';
import {
  Finding,
  FindingEntry,
  transformFindingsToObjectiveEntries,
} from '@shared/models/finding.model';
import {NbGetters, NbTreeGridDataSource, NbTreeGridDataSourceBuilder} from '@nebular/theme';
import * as FA from '@fortawesome/free-solid-svg-icons';
import {isNotNullOrUndefined} from 'codelyzer/util/isNotNullOrUndefined';
import {FindingDialogService} from '@shared/modules/finding-dialog/service/finding-dialog.service';
import {FindingDialogComponent} from '@shared/modules/finding-dialog/finding-dialog.component';
import {PentestStatus} from '@shared/models/pentest-status.model';
import {Store} from '@ngxs/store';
import {UpdatePentestFindings} from '@shared/stores/project-state/project-state.actions';
import {ProjectState} from '@shared/stores/project-state/project-state';
import {DialogService} from '@shared/services/dialog-service/dialog.service';
import {FindingService} from '@shared/services/api/finding.service';

@UntilDestroy()
@Component({
  selector: 'app-pentest-findings',
  templateUrl: './pentest-findings.component.html',
  styleUrls: ['./pentest-findings.component.scss']
})
export class PentestFindingsComponent implements OnInit {

  constructor(private findingService: FindingService,
              private dataSourceBuilder: NbTreeGridDataSourceBuilder<FindingEntry>,
              private readonly notificationService: NotificationService,
              private dialogService: DialogService,
              private findingDialogService: FindingDialogService,
              private store: Store) {
    this.dataSource = dataSourceBuilder.create(this.data, this.getters);
  }

  pentestInfo$: BehaviorSubject<Pentest> = new BehaviorSubject<Pentest>(null);
  loading$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);

  // HTML only
  readonly fa = FA;
  // HTML only for button enabling
  inProgressStatus: PentestStatus = PentestStatus.IN_PROGRESS;

  columns: Array<FindingColumns> = [
    FindingColumns.TITLE, FindingColumns.SEVERITY, FindingColumns.DESCRIPTION, FindingColumns.IMPACT, FindingColumns.ACTIONS
  ];
  dataSource: NbTreeGridDataSource<FindingEntry>;

  data: FindingEntry[] = [];

  getters: NbGetters<FindingEntry, FindingEntry> = {
    dataGetter: (node: FindingEntry) => node,
    childrenGetter: (node: FindingEntry) => node.childEntries || undefined,
    expandedGetter: (node: FindingEntry) => !!node.expanded,
  };

  ngOnInit(): void {
    this.store.select(ProjectState.pentest).pipe(
      untilDestroyed(this)
    ).subscribe({
      next: (selectedPentest: Pentest) => {
        this.pentestInfo$.next(selectedPentest);
        this.loadFindingsData();
      },
      error: err => {
        console.error(err);
      }
    });
  }

  loadFindingsData(): void {
    this.findingService.getFindingsByPentestId(this.pentestInfo$.getValue() ? this.pentestInfo$.getValue().id : '')
      .pipe(
        untilDestroyed(this),
        /*filter(isNotNullOrUndefined),*/
        tap(() => this.loading$.next(true))
      )
      .subscribe({
        next: (findings: Finding[]) => {
          // ToDo: Handle this case before in pipe
          if (findings) {
            this.data = transformFindingsToObjectiveEntries(findings);
          } else {
            this.data = [];
          }
          this.dataSource.setData(this.data, this.getters);
          this.loading$.next(false);
        },
        error: err => {
          console.error(err);
          // ToDo: Implement again after proper lazy loading and routing
          // this.notificationService.showPopup('findings.popup.not.found', PopupType.FAILURE);
          this.loading$.next(false);
        }
      });
  }

  onClickAddFinding(): void {
    this.findingDialogService.openFindingDialog(
      FindingDialogComponent,
      null,
      {
        closeOnEsc: false,
        hasScroll: false,
        autoFocus: true,
        closeOnBackdropClick: false
      },
      this.pentestInfo$.getValue()
    ).pipe(
      untilDestroyed(this)
    ).subscribe({
      next: (newFinding: Finding) => {
        this.loadFindingsData();
      }
    });
  }

  onClickEditFinding(findingEntry): void {
    this.findingService.getFindingById(findingEntry.data.findingId).pipe(
      filter(isNotNullOrUndefined),
      untilDestroyed(this)
    ).subscribe({
      next: (existingFinding: Finding) => {
        if (existingFinding) {
          this.findingDialogService.openFindingDialog(
            FindingDialogComponent,
            existingFinding,
            {
              closeOnEsc: false,
              hasScroll: false,
              autoFocus: true,
              closeOnBackdropClick: false
            },
            this.pentestInfo$.getValue()
          ).pipe(
            untilDestroyed(this)
          ).subscribe({
            next: (updatedFinding: Finding) => {
              this.loadFindingsData();
            }
          });
        } else {
          this.notificationService.showPopup('finding.popup.not.available', PopupType.INFO);
        }
      },
      error: err => {
        console.error(err);
      }
    });
  }

  onClickDeleteFinding(findingEntry): void {
    const message = {
      title: 'finding.delete.title',
      key: 'finding.delete.key',
      data: {name: findingEntry.data.title},
    };
    this.dialogService.openConfirmDialog(
      message
    ).onClose.pipe(
      untilDestroyed(this)
    ).subscribe({
      next: () => {
        this.deleteFinding(findingEntry);
      }
    });
  }

  isLoading(): Observable<boolean> {
    return this.loading$.asObservable();
  }

  private deleteFinding(findingEntry): void {
    this.findingService.deleteFindingByPentestAndFindingId(
      this.pentestInfo$.getValue() ? this.pentestInfo$.getValue().id : '',
      findingEntry.data.findingId)
      .pipe(
        untilDestroyed(this)
      ).subscribe({
      next: (deletedFinding: any) => {
        this.store.dispatch(new UpdatePentestFindings(deletedFinding.id));
        this.loadFindingsData();
        this.notificationService.showPopup('finding.popup.delete.success', PopupType.SUCCESS);
      }, error: error => {
        console.error(error);
        this.onRequestFailed(findingEntry);
        this.notificationService.showPopup('finding.popup.delete.failed', PopupType.FAILURE);
      }
    });
  }

  private onRequestFailed(retryParameter: any): void {
    this.dialogService.openRetryDialog({key: 'global.retry.dialog', data: null}).onClose
      .pipe(
        untilDestroyed(this)
      )
      .subscribe((ref) => {
        if (ref.retry) {
          this.deleteFinding(retryParameter);
        }
      });
  }
}

enum FindingColumns {
  FINDING_ID = 'findingId',
  TITLE = 'title',
  SEVERITY = 'severity',
  DESCRIPTION = 'description',
  IMPACT = 'impact',
  ACTIONS = 'actions'
}
