import {AfterViewInit, ChangeDetectorRef, Component, Input, OnInit, ViewChild} from "@angular/core";
import {Role, User} from "../login/utils/helper.class";
import {ActivatedRoute, Router} from "@angular/router";
import {UserManagementService} from "../services/user-management.service";
import {UserRegistryService} from "../services/user-registry.service";
import {LoginErrorCodes} from "../login/utils/guardHelper.class";
import {Subscription} from "rxjs";
import {UntypedFormBuilder, UntypedFormControl, Validators} from "@angular/forms";
import {AlertModal} from "../utils/modal/alert";
import {properties} from "../../../environments/environment";
import {EmailService} from "../utils/email/email.service";
import {Composer} from "../utils/email/composer";
import {ClearCacheService} from "../services/clear-cache.service";
import {BaseComponent} from "../sharedComponents/base/base.component";
import {StakeholderUtils} from "../monitor-admin/utils/indicator-utils";
import {StringUtils} from "../utils/string-utils.class";

@Component({
  selector: 'role-verification',
  template: `
    <modal-alert #managerModal [overflowBody]="false" (alertOutput)="verifyManager()" (cancelOutput)="cancel()"
                 [okDisabled]="code.invalid || loading">
      <div>
        You have been invited to join <span class="uk-text-bold">{{name}}</span> {{(dashboard)}} Dashboard as a {{stakeholderUtils.roles.manager}}.
        <span class="uk-text-primary">Fill</span> in the <span class="uk-text-primary">verification code</span>, sent to
        your email, to accept the invitation request.
      </div>
      <div *ngIf="!loading" class="uk-margin-medium-top uk-flex uk-flex-center">
        <div input [formInput]="code" class="uk-width-medium" placeholder="Verification code">
          <span *ngIf="error" error>{{error}}</span>
        </div>
      </div>
      <div *ngIf="loading" class="uk-margin-medium-top uk-flex uk-flex-center">
        <loading></loading>
      </div>
    </modal-alert>
    <modal-alert #memberModal [overflowBody]="false" (cancelOutput)="cancel()"
                 (alertOutput)="verifyMember()" [okDisabled]="(code.invalid || loading)">
      <div>
        <div>
          You have been invited to join <span class="uk-text-bold">{{name}}</span> {{(dashboard)}} Dashboard as a {{stakeholderUtils.roles.member}}.
          <span class="uk-text-primary">Fill</span> in the <span class="uk-text-primary">verification code</span>, sent
          to your email, to accept the invitation request.
        </div>
        <div *ngIf="!loading" class="uk-margin-medium-top uk-flex uk-flex-wrap uk-flex-center">
          <div input [formInput]="code" class="uk-width-medium" placeholder="Verification code">
            <span *ngIf="error" error>{{error}}</span>
          </div>
        </div>
        <div *ngIf="loading" class="uk-margin-medium-top">
          <loading></loading>
        </div>
      </div>
    </modal-alert>
    <modal-alert #errorModal (alertOutput)="cancel()" [overflowBody]="false">
      <div>
        We are unable to process the request. What happened?
        <ul class="uk-margin-top uk-list uk-list-circle uk-list-primary">
          <li>You are logged in with a different email, than the one you have received the invitation.
            Check
            <a *ngIf="!userInfoLink" [routerLink]="[userInfoLinkPrefix + '/user-info']" (click)="errorModal.cancel()">here</a>
            <a *ngIf="userInfoLink" [href]="userInfoLink" (click)="errorModal.cancel()">here</a>
            the email of your account.</li>
          <li>The invitation has been canceled.</li>
          <li>The URL is invalid.</li>
        </ul>
      </div>
    </modal-alert>
  `
})
export class RoleVerificationComponent extends BaseComponent implements OnInit, AfterViewInit {
  @Input()
  public id: string;
  @Input()
  set type(type: string) {
    this._type = Role.GROUP + type;
  }
  @Input()
  public name: string;
  @Input()
  public service: "connect" | "monitor" | "irish" = "monitor";
  @Input()
  public userInfoLinkPrefix = '';
  @Input()
  public userInfoLink = null;
  @Input()
  public relativeTo: ActivatedRoute = this._route;
  @Input()
  public dashboard: string = 'Research Community';
  public user: User;
  public verification: any;
  public code: UntypedFormControl;
  private _type: string;
  private paramsSubscription: Subscription;
  @ViewChild('managerModal') managerModal: AlertModal;
  @ViewChild('memberModal') memberModal: AlertModal;
  @ViewChild('errorModal') errorModal: AlertModal;
  public error: string = null;
  public loading: boolean = false;
  public stakeholderUtils: StakeholderUtils = new StakeholderUtils();

  constructor(protected _route: ActivatedRoute,
              protected _router: Router,
              private fb: UntypedFormBuilder,
              private emailService: EmailService,
              private userManagementService: UserManagementService,
              private userRegistryService: UserRegistryService,
              private clearCacheService: ClearCacheService,
              private cdr: ChangeDetectorRef) {
    super();
  }

  ngOnInit() {
    this.reset();
  }

  ngAfterViewInit() {
    this.init();
  }

  init() {
    this.ngOnDestroy();
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      this.paramsSubscription = this._route.queryParams.subscribe(params => {
        if (params) {
          this.cdr.detectChanges();
          if(params['verify']) {
            if (this.user) {
              this.subscriptions.push(this.userRegistryService.getInvitation(params['verify']).subscribe(verification => {
                this.verification = verification;
                if (this.user.email === this.verification.email.toLowerCase() && this.id === this.verification.entity && this._type === this.verification.type) {
                  if (this.verification.verificationType === 'manager') {
                    this.openManagerModal();
                  } else if (this.verification.verificationType === 'member') {
                    this.openMemberModal();
                  } else {
                    this.openErrorModal();
                  }
                } else {
                  this.openErrorModal();
                }
              }, error => {
                this.openErrorModal();
              }));
            } else {
              this._router.navigate(['user-info'], {
                queryParams: {
                  'errorCode': LoginErrorCodes.NOT_LOGIN,
                  'redirectUrl': this._router.url
                },
                relativeTo: this.relativeTo
              });
            }
          } else if(this.isMember) {
            this.openMemberModal();
          }
        } else {
          this.isMember = false;
          this.cdr.detectChanges();
        }
      });
    }));
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.paramsSubscription instanceof Subscription) {
      this.paramsSubscription.unsubscribe();
    }
  }

  public openManagerModal() {
    this.error = null;
    this.managerModal.okButtonLeft = false;
    this.managerModal.okButtonText = 'Accept';
    this.managerModal.stayOpen = true;
    this.managerModal.cancelButtonText = 'Cancel';
    this.managerModal.alertTitle = StringUtils.capitalize(this.stakeholderUtils.roles.manager) + ' Invitation';
    this.managerModal.open();
  }

  public openMemberModal() {
    this.error = null;
    this.memberModal.cancelButton = true;
    this.memberModal.okButtonText = 'Accept';
    this.memberModal.okButtonLeft = false;
    this.memberModal.stayOpen = true;
    this.memberModal.cancelButtonText = 'Cancel';
    this.memberModal.alertTitle = StringUtils.capitalize(this.stakeholderUtils.roles.member)  + ' Invitation';
    this.cdr.detectChanges();
    this.memberModal.open();
  }

  public openErrorModal() {
    this.error = null;
    this.errorModal.cancelButton = false;
    this.errorModal.okButtonText = 'Ok';
    this.errorModal.alertTitle = 'Invalid URL';
    this.errorModal.open();
  }

  public verifyManager() {
    this.loading = true;
    this.subscriptions.push(this.userRegistryService.verify(this.verification.id, this.code.value).subscribe(() => {
      // this.clearCacheService.clearCache('Managers updated');
      this.managerModal.cancel();
      this.error = null;
      if(this.service === "irish" || this.service === "monitor") {
        this.loading = false;
        this.userManagementService.login(properties.domain + '/admin/' + this.verification.entity);
      } else {
        this.subscriptions.push(this.emailService.notifyManagers(this.id, 'manager',
            Composer.composeEmailToInformOldManagersForTheNewOnes(this.name, this.id)).subscribe(() => {
          this.subscriptions.push(this.emailService.notifyNewManager(Composer.composeEmailForNewManager(this.id, this.name)).subscribe(
              () => {
                this.loading = false;
                window.location.href = properties.adminPortalURL + '/' + this.verification.entity;
              },
              error1 => {
                console.error(error1);
                this.loading = false;
                window.location.href = properties.adminPortalURL + '/' + this.verification.entity;
              }
          ));
        }, error => {
          console.error(error);
          this.loading = false;
          window.location.href = properties.adminPortalURL + '/' + this.verification.entity;
        }));
      }
    }, error => {
      this.loading = false;
      this.error = 'The verification code is invalid';
    }));
  }

  public verifyMember() {
    this.loading = true;
      this.subscriptions.push(this.userRegistryService.verify(this.verification.id, this.code.value, "member").subscribe(() => {
       // this.clearCacheService.clearCache('Members updated');
        this.memberModal.cancel();
        this.loading = false;
        this.error = null;
        window.location.href = window.location.href.split('?')[0];
      }, error => {
        this.loading = false;
        this.error = 'The verification code is invalid';
      }));
  }

  public reset() {
    this.code = this.fb.control('', [Validators.required, Validators.pattern('^[+0-9]{6}$')]);
  }

  cancel() {
    this._router.navigate([]);
  }
}
