import {Component, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {UserComponent} from '../openaireLibrary/login/user.component';
import {EmailService} from "../openaireLibrary/utils/email/email.service";

import {Session, User} from '../openaireLibrary/login/utils/helper.class';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {SubscribeComponent} from '../utils/subscribe/subscribe.component';
import {ConnectHelper} from '../openaireLibrary/connect/connectHelper';
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";

@Component({
  selector: 'openaire-user',
  template: `
    <div id="tm-main" class="uk-section tm-middle">
      <div class="uk-margin-small-top">
        <user [mainComponent]=false></user>
        <div   class=" uk-container uk-container-small uk-position-relative">
          <div *ngIf="usercomponent.errorCode == '6' && !isSubscribed" class="uk-alert uk-alert-warning">
            <span *ngIf="!isSubscribed ">For this action you have to <span *ngIf="!loggedIn">login and</span> subscribe to the research community.
              <span *ngIf="subscribe && !subscribeLoading "> <span *ngIf="!loggedIn">Login and </span>Subscribe <a
                [class]="'' + (subscribe.loading ? ' uk-disabled' : '')" (click)="subscribeTo()"> here</a>.</span>
            </span>
            <span *ngIf="subscribeLoading ">Subscribing to community....</span>
            <span *ngIf="subscribeError ">An error occured while trying to subscribe to community....</span>

          </div>           
        </div>
      </div>
    </div>
    <subscribe [communityId]="communityId" [showTemplate]=false class=""
               (subscribeEvent)="afterSubscibeEvent($event)"></subscribe>
  `
})

export class OpenaireUserComponent {
  @ViewChild(UserComponent, { static: true }) usercomponent: UserComponent;
  @ViewChild(SubscribeComponent, { static: true }) subscribe: SubscribeComponent;
  properties: EnvProperties;
  communityId = null;
  subscribeLoading: boolean = false;
  subscribeError: boolean = false;
  isSubscribed: boolean = false;
  public server: boolean = true;
  loggedIn: boolean = false;
  private subscriptions = [];
  public user: User;
  public redirectUrl: string = "";
  constructor(private _emailService: EmailService, private route: ActivatedRoute,
              private userManagementsService: UserManagementService) {
  }
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  public ngOnInit() {
    if (typeof document !== 'undefined') {
      this.server = false;
    }
    this.userManagementsService.updateUserInfo(() => {
      this.user = this.userManagementsService.user;
      this.loggedIn = !!this.user;
      this.isSubscribed = this.loggedIn && Session.isSubscribedTo('community', this.communityId, this.user);
      if (this.isSubscribed) {
        this.usercomponent.redirect(this.redirectUrl);
      }
    });
    this.properties = properties;
    this.subscriptions.push(this.route.queryParams.subscribe(
      params => {
        this.redirectUrl = params["redirectUrl"];
        this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
        if (!this.communityId) {
          this.communityId = params['communityId'];
        }
        if (this.isSubscribed) {
          this.isSubscribed = true;
          this.usercomponent.redirect(this.redirectUrl);
        }
      }));
  }


  login() {
    this.usercomponent.logIn();

  }

  subscribeTo() {
    if(!this.loggedIn){
      this.login();
      return;
    }

    if (!this.isSubscribed && this.communityId) {
      this.subscribeLoading = true;
      this.subscribe.subscribe();
    }
  }

  afterSubscibeEvent($event) {
    var res = $event.value;
    this.subscribeLoading = false;
    this.isSubscribed = this.subscribe.subscribed;
    if (res == "ok") {
      this.isSubscribed = true;
      this.usercomponent.redirect();
    } else {
      this.subscribeError = true;
    }

  }

}
