import {Component, EventEmitter, Input, Output, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {AlertModal} from '../../openaireLibrary/utils/modal/alert';

import {CommunityService} from '../../openaireLibrary/connect/community/community.service';
import {SubscribeService} from '../../openaireLibrary/utils/subscribe/subscribe.service';
import {EmailService} from "../../openaireLibrary/utils/email/email.service";
import {Session, User} from '../../openaireLibrary/login/utils/helper.class';

import {Email} from "../../openaireLibrary/utils/email/email";
import {Composer} from "../../openaireLibrary/utils/email/composer";
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {UserManagementService} from "../../openaireLibrary/services/user-management.service";

declare var UIkit: any;

@Component({
  selector: 'subscribe',
  template: `

    <span *ngIf="subscribed != null && !showNumbers && showTemplate">
      <div *ngIf="!subscribed && showLoginAlert" class="uk-alert-warning uk-animation-slide-bottom" uk-alert="">
      <a class="uk-alert-close" uk-close></a>
      <p>Please login first to subscribe</p>
      </div>
      <button *ngIf="!subscribed" [class]="'uk-button uk-button-primary' + (loading ? ' uk-disabled' : '')"
              (click)="subscribe()"> Subscribe</button>
      <button *ngIf="subscribed" [class]="'uk-button uk-button-primary' + (loading ? ' uk-disabled' : '')"
              (click)="confirmOpen()"> Unsubscribe</button>
    </span>

    <span *ngIf="showNumbers && subscribers !=null && subscribers > 0  && showTemplate">
      <span class="lowOpacityColor">  Members</span> {{subscribers}}
    </span>
    <modal-alert (alertOutput)="confirmClose($event)">
    </modal-alert>
  `
})

export class SubscribeComponent {
  // @Input() showSubscribe:boolean = true;
  @Input() showNumbers: boolean;
  @Input() communityId: string;
  @Input() showTemplate: boolean = true;
  @Output() subscribeEvent = new EventEmitter();

  public community = null;
  public emailToInformManagers: Email;

  loading: boolean = false;
  subscribed: boolean = null;
  properties: EnvProperties;
  subscribers: number = null;
  showLoginAlert: Boolean = false;
  @ViewChild(AlertModal) alert;
  private user: User;

  constructor(private route: ActivatedRoute,
              private _subscribeService: SubscribeService,
              private _emailService: EmailService,
              private _communityService: CommunityService,
              private router: Router,
              private userManagementService: UserManagementService
  ) {
  }

  public ngOnInit() {
    this.route.data
      .subscribe((data: { envSpecific: EnvProperties }) => {
        this.properties = data.envSpecific;
        this.userManagementService.getUserInfo().subscribe(user => {
          this.user = user;
          if (!this.showNumbers) {
            let email = (this.user)?this.user.email:null;
            if (email == null) {
              this.subscribed = false;
            } else {
              if (this.communityId) {
                this._subscribeService.isSubscribedToCommunity(this.properties, this.communityId).subscribe(
                  res => {
                    this.subscribed = res;
                    if (this.subscribed) {
                      this.subscribeEvent.emit({
                        value: "ok"
                      });
                    }
                  },
                  error => {
                    this.handleError("Error getting response if email: " + email + " is subscribed to community with id: " + this.communityId, error);
                  });
              }
            }
          } else {
            if (this.communityId) {
              this._subscribeService.getCommunitySubscribers(this.properties, this.communityId).subscribe(
                res => {
                  this.subscribers = (res && res.subscribers && res.subscribers.length) ? res.subscribers.length : 0;
                },
                error => {
                  this.handleError("Error getting community subscribers for community with id: " + this.communityId, error);
                });
            }
          }
          if (this.communityId) {
            this.emailToInformManagers = {body: "", subject: "", recipients: []};

            this._communityService.getCommunity(this.properties, this.properties.communityAPI + this.communityId).subscribe(
              community => {
                this.community = community;
              },
              error => {
                //console.log('System error retrieving community profile', error)
                this.handleError("Error getting community with id: " + this.communityId, error);
              }
            );
          }
        });
      });
  }

  subscribe() {
    var email = (this.user)?this.user.email:null;
    if (email == null) {
      this.subscribed = false;
      // this.showLoginAlert = true;
      this.router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.ACTION_REQUIRES_LOGIN,
          "redirectUrl": this.properties.baseLink + this.router.url
        }
      });
    } else {
      this.loading = true;
      this.showLoginAlert = false;
      this._subscribeService.subscribeToCommunity(this.properties, this.communityId).subscribe(
        res => {
          this.loading = false;
          if (res.status && res.status != 200) {
            this.subscribeEvent.emit({
              value: "error"
            });
            UIkit.notification({
              message: '<strong>An error occured. Please try again!<strong>',
              status: 'warning',
              timeout: 3000,
              pos: 'top-center'
            });
          } else {
            if (!this.subscribed) {
              this.subscribed = true;
              this.subscribeEvent.emit({
                value: "ok"
              });
              this._emailService.sendEmail(this.properties,
                Composer.composeEmailToInformManagers(this.community.title, this.communityId, this.community.managers, email, this.properties.adminPortalURL)).subscribe(
                res => {
                  //console.log("The email has been sent successfully!")
                },
                error => {
                  //console.log(error)
                  this.handleError("Error notifying managers about new subscribers for community with id: " + this.communityId, error);
                }
              );
            }
          }
        },
        error => {
          this.loading = false;
          this.subscribeEvent.emit({
            value: "error"
          });
          UIkit.notification({
            message: '<strong>An error occured. Please try again!<strong>',
            status: 'warning',
            timeout: 3000,
            pos: 'top-center'
          });
          //console.log(error)
          this.handleError("Error subscribing email: " + email + " to community with id: " + this.communityId, error);
        });
    }
  }

  unsubscribe() {
    var email = (this.user)?this.user.email:null;
    if (email == null) {
      this.subscribed = false;
    } else {
      this.loading = true;
      //this.properties.adminToolsAPIURL
      this._subscribeService.unSubscribeToCommunity(this.properties, this.communityId).subscribe(
        res => {
          this.loading = false;
          if (res.status && res.status != 200) {
            UIkit.notification({
              message: '<strong>An error occured. Please try again!<strong>',
              status: 'warning',
              timeout: 3000,
              pos: 'top-center'
            });
          } else {
            //console.log(res);
            if (this.subscribed) {
              console.log('here')
              this.subscribed = false;
            }
          }
        },
        error => {
          this.loading = false;
          UIkit.notification({
            message: '<strong>An error occured. Please try again!<strong>',
            status: 'warning',
            timeout: 3000,
            pos: 'top-center'
          });
          //console.log(error)
          this.handleError("Error unsubscribing email: " + email + " from community with id: " + this.communityId, error);
        });
    }
  }

  confirmOpen() {

    this.alert.cancelButton = true;
    this.alert.okButton = true;
    this.alert.alertTitle = "Unsubscribe community ";
    this.alert.message = "Do you want to proceed? ";
    this.alert.okButtonText = "Yes";
    this.alert.cancelButtonText = "No";
    this.alert.open();
  }

  confirmClose(data) {
    this.unsubscribe();
  }

  private handleError(message: string, error) {
    console.error("Subscribe (component): " + message, error);
  }
}
