import {Component, OnInit, Input, ViewChild, ElementRef} from '@angular/core';
import {FormGroup, FormBuilder} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';

import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';

import {Session, User} from '../../openaireLibrary/login/utils/helper.class';

import {ManageUserNotificationsService} from './manage-user-notifications.service';

import {UserNotificationsRights} from './userNotificationsRights';

import {MailPrefsComponent} from '../../openaireLibrary/connect/userEmailPreferences/mailPrefs.component';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from '../../openaireLibrary/utils/HelperFunctions.class';
import {UserManagementService} from '../../openaireLibrary/services/user-management.service';
import {Title} from '@angular/platform-browser';

@Component({
  selector: 'manage-user-notifications',
  templateUrl: './manage-user-notifications.component.html',
})

export class ManageUserNotificationsComponent implements OnInit {

  @Input('group')
  myForm: FormGroup;

  public properties: EnvProperties = null;
  public communityId = null;
  public userNotifications = null;
  public initialUserNotifications = null;
  public userEmail = null;

  public showLoading = true;
  public errorMessage = '';
  public updateErrorMessage = '';

  public successfulSaveMessage = '';
  public successfulResetMessage = '';

  public hasChanged = false;
  public user: User;

  @ViewChild(MailPrefsComponent) mailPrefs: MailPrefsComponent;

  constructor(private route: ActivatedRoute, private _router: Router, public _fb: FormBuilder,
              private title: Title,
              private _manageUserNotificationsService: ManageUserNotificationsService,
              private element: ElementRef, private userManagementService: UserManagementService) {
  }

  ngOnInit() {
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
      this.properties = data.envSpecific;
      this.route.queryParams.subscribe(
        communityId => {
          HelperFunctions.scroll();
          this.communityId = communityId['communityId'];
          if (this.communityId != null && this.communityId !== '') {
            this.title.setTitle('Administration Dashboard | User Notifications');
            this.showLoading = true;
            this.updateErrorMessage = '';
            this.errorMessage = '';
            this.successfulSaveMessage = '';
            this.userManagementService.getUserInfo().subscribe(user => {
                this.user = user;
                if (this.user) {
                    this.userEmail = this.user.email;
                    this._manageUserNotificationsService.getUserNotifications(this.properties, this.communityId, this.userEmail).subscribe(
                      userNotifications => {
                          this.initialUserNotifications = userNotifications;
                          if (this.initialUserNotifications['notifyForNewManagers'] == null ||
                            this.initialUserNotifications['notifyForNewSubscribers'] == null) {
                              this.initialUserNotifications = this.initiateUserNotifications();
                          }

                          this.userNotifications = JSON.parse(JSON.stringify(this.initialUserNotifications));

                          // TODO remove after final testing
                          this.showLoading = false;
                      },
                      error => {
                          if (error.status === 404) {
                              this.initialUserNotifications = this.initiateUserNotifications();
                              this.userNotifications = JSON.parse(JSON.stringify(this.initialUserNotifications));
                          } else {
                              this.handleError('System error retrieving user notifications', error);
                          }
                          this.showLoading = false;
                      }
                    );
                }
            });
            }
          }
        );
    });
  }

  public initiateUserNotifications(): UserNotificationsRights {
    const notificationRights: UserNotificationsRights = new UserNotificationsRights();

    notificationRights['notifyForNewManagers'] = true;
    notificationRights['notifyForNewSubscribers'] = true;
    notificationRights['managerEmail'] = this.userEmail;

    return notificationRights;
  }

  public updateUserNotifications() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'],
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      if (this.communityId != null && this.communityId !== '') {
        this.mailPrefs.saveNotification(0);

        this.successfulSaveMessage = '';
        this.showLoading = true;
        const userNotifications = this.parseUpdatedUserNotifications();
        this._manageUserNotificationsService.updateUserNotifications(this.properties, this.communityId, userNotifications).subscribe(
          userNotifications => {
            this.initialUserNotifications = JSON.parse(JSON.stringify(this.userNotifications));
            this.handleSuccessfulSave('Notification settings saved!');
          },
          error => this.handleUpdateError('System error updating user notifications', error)
        );
      }
      this.resetChange();
    }
  }

  private parseUpdatedUserNotifications(): {} {
    const userNotifications = {};

    userNotifications['notifyForNewManagers'] = this.userNotifications.notifyForNewManagers;
    userNotifications['notifyForNewSubscribers'] = this.userNotifications.notifyForNewSubscribers;

    if (this.userNotifications.managerEmail) {
      userNotifications['managerEmail'] = this.userNotifications.managerEmail;
    } else {
      if (this.user) {
        userNotifications['managerEmail'] = this.user.email;
      }
    }
    return userNotifications;
  }

  public resetForm() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      this.mailPrefs.restoreNotification(0);
      if (this.userNotifications && this.initialUserNotifications) {
        this.successfulSaveMessage = '';
        this.showLoading = true;
        this.userNotifications = JSON.parse(JSON.stringify(this.initialUserNotifications));
        this.showLoading = false;
      }
      this.resetChange();
    }
  }

  public changeValueForNewManagers(notifyForManagers: any) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {' "errorCode"': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      this.userNotifications.notifyForNewManagers = !notifyForManagers;
      this.change();
    }
  }

  public changeValueForNewSubscribers(notifyForSubscribers: any) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      this.userNotifications.notifyForNewSubscribers = !notifyForSubscribers;
      this.change();
    }
  }

  private change() {
    this.hasChanged = true;
    this.successfulSaveMessage = '';
    this.successfulResetMessage = '';
  }

  private resetChange() {
    this.hasChanged = false;
  }

  public mailPrefsChanged(): boolean {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      return this.mailPrefs.prefsChanged['0'];
    }
  }

  handleUpdateError(message: string, error) {
    this.updateErrorMessage = message;
    console.log('Server responded: ' + error);

    this.showLoading = false;
  }

  handleError(message: string, error) {
    this.errorMessage = message;
    console.log('Server responded: ' + error);

    this.showLoading = false;
  }

  handleSuccessfulSave(message) {
    this.showLoading = false;
    this.successfulSaveMessage = message;
  }

  handleSuccessfulReset(message) {
    this.showLoading = false;
    this.successfulResetMessage = message;
  }
}
