import { Component, Inject, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DepositConfigurationStatus } from '@app/core/common/enum/deposit-configuration-status';
import { DepositConfigurationModel } from '@app/core/model/deposit/deposit-configuration';
import { DmpOverviewModel } from '@app/core/model/dmp/dmp-overview';
import { DoiModel } from '@app/core/model/doi/doi';
import { DepositRepositoriesService } from '@app/core/services/deposit-repositories/deposit-repositories.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { Oauth2DialogService } from '@app/ui/misc/oauth2-dialog/service/oauth2-dialog.service';
import { BaseComponent } from '@common/base/base.component';
import { MultipleChoiceDialogComponent } from '@common/modules/multiple-choice-dialog/multiple-choice-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-dmp-deposit-dialog',
  templateUrl: './dmp-deposit-dialog.component.html',
  styleUrls: ['./dmp-deposit-dialog.component.scss']
})
export class DmpDepositDialogComponent extends BaseComponent implements OnInit {

  inputRepos: DepositConfigurationModel[];
  outputRepos: DoiModel[];
  dmp: DmpOverviewModel;
  private oauthLock: boolean;

  constructor(
    private depositRepositoriesService: DepositRepositoriesService,
    public dialogRef: MatDialogRef<DmpDepositDialogComponent>,
    private dialog: MatDialog,
    private language: TranslateService,
    private translate: TranslateService,
    private uiNotificationService: UiNotificationService,
    private oauth2DialogService: Oauth2DialogService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    super();
    this.inputRepos = data['depositRepos'][0];
    this.dmp = data['depositRepos'][1];
    for(var i = 0; i < this.dmp.dois.length; i++){ 
      this.inputRepos = this.inputRepos.filter(r => this.hasDoi(r, this.dmp.dois, i));
    }
    this.outputRepos = [];
   }

  hasDoi(repo, dois, i){
    return repo.repositoryId !== dois[i].repositoryId;
  }

  ngOnInit(): void {
  }

  onSubmit() {
		this.dialogRef.close(this.outputRepos);
	}

  close() {
		this.dialogRef.close(this.outputRepos);
	}

  deposit(repo: DepositConfigurationModel) {

    if(repo.depositType == DepositConfigurationStatus.BothSystemAndUser){

      const dialogRef = this.dialog.open(MultipleChoiceDialogComponent, {
        maxWidth: '600px',
        restoreFocus: false,
        data: {
          message: this.language.instant('DMP-OVERVIEW.DEPOSIT.ACCOUNT-LOGIN'),
          titles: [this.language.instant('DMP-OVERVIEW.DEPOSIT.LOGIN', { 'repository': repo.repositoryId }), this.language.instant('DMP-OVERVIEW.MULTIPLE-DIALOG.USE-DEFAULT')]
        }
      });
      dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
        switch (result) {
          case 0:
            this.showOauth2Dialog(repo.repositoryAuthorizationUrl + '?client_id=' + repo.repositoryClientId
            + '&response_type=code&scope=deposit:write+deposit:actions+user:email&state=astate&redirect_uri='
            + repo.redirectUri, repo, this.dmp);
            break;
          case 1:
            this.depositRepositoriesService.createDoi(repo.repositoryId, this.dmp.id, null)
                .pipe(takeUntil(this._destroyed))
                .subscribe(doi =>{
                  this.onDOICallbackSuccess();
                  this.outputRepos.push(doi);
                  this.inputRepos = this.inputRepos.filter(function(x) { return x.repositoryId !== repo.repositoryId; });
                  if(this.inputRepos.length == 0){
                    this.close();
                  }
                }, error => this.onDOICallbackError(error));
            break;
        }
		  });

    }
    else if(repo.depositType == DepositConfigurationStatus.System){
      this.depositRepositoriesService.createDoi(repo.repositoryId, this.dmp.id, null)
        .pipe(takeUntil(this._destroyed))
        .subscribe(doi =>{
          this.onDOICallbackSuccess();
          this.outputRepos.push(doi);
          this.inputRepos = this.inputRepos.filter(function(x) { return x.repositoryId !== repo.repositoryId; });
          if(this.inputRepos.length == 0){
            this.close();
          }
        }, error => this.onDOICallbackError(error));
    }
  }

  onDOICallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('DMP-EDITOR.SNACK-BAR.SUCCESSFUL-DOI'), SnackBarNotificationLevel.Success);
	}

  onDOICallbackError(error) {
		this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('DMP-EDITOR.SNACK-BAR.UNSUCCESSFUL-DOI'), SnackBarNotificationLevel.Error);
	}

  showOauth2Dialog(url: string, repo: DepositConfigurationModel, dmp: DmpOverviewModel) {
		this.oauth2DialogService.login(url)
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (result !== undefined) {
					if (result.oauthCode !== undefined && result.oauthCode !== null && !this.oauthLock) {
            this.depositRepositoriesService.getAccessToken(repo.repositoryId, result.oauthCode)
            .pipe(takeUntil(this._destroyed))
            .subscribe(token => {
                this.depositRepositoriesService.createDoi(repo.repositoryId, dmp.id, token)
                .pipe(takeUntil(this._destroyed))
                .subscribe(doi =>{
                  this.onDOICallbackSuccess();
                  this.outputRepos.push(doi);
                  this.inputRepos = this.inputRepos.filter(function(x) { return x.repositoryId !== repo.repositoryId; });
                  if(this.inputRepos.length == 0){
                    this.close();
                  }
                }, error => this.onDOICallbackError(error));
            });
            this.oauthLock = true;
					}
				}
        else{
          this.oauthLock = false;
        }
			});
	}

}
