import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';

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

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {Affiliation} from '../../openaireLibrary/utils/entities/CuratorInfo';
import {HelperFunctions} from '../../openaireLibrary/utils/HelperFunctions.class';
import {AlertModal} from '../../openaireLibrary/utils/modal/alert';
import {UtilitiesService} from '../../openaireLibrary/services/utilities.service';
import {AffiliationService} from "../../openaireLibrary/connect/affiliations/affiliation.service";
import {HelpContentService} from "../../services/help-content.service";
import {Title} from '@angular/platform-browser';

@Component({
  selector: 'affiliations',
  templateUrl: './affiliations.component.html',
})

export class AffiliationsComponent implements OnInit {

  @ViewChild('affiliationModal') affiliationModal: AlertModal;
  @ViewChild('removeAffiliationModal') removeAffiliationModal: AlertModal;
  public showLoading = false;
  public message = '';
  public messageType = '';

  public affiliation: Affiliation = new Affiliation();
  public properties: EnvProperties = null;

  private index = 0;
  private maxCharacters = 70;

  @Input() hasChanged: boolean = false;
  @Input() curatorAffiliations: boolean = false;
  @Input() public affiliations: Affiliation[] = [];
  @Output() affiliationsChange: EventEmitter<boolean> = new EventEmitter();
  @Output() resetCuratorMessages: EventEmitter<boolean> = new EventEmitter();
  public communityId: string;
  public organizationsPageId: string;
  public organizationsEnabled = false;

  constructor(private element: ElementRef,
              private route: ActivatedRoute,
              private _router: Router,
              private title: Title,
              private affiliationService: AffiliationService,
              private _helpContentService: HelpContentService) {
  }


  ngOnInit() {
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
      this.properties = data.envSpecific;
      if(!this.curatorAffiliations) {
        this.title.setTitle('Administration Dashboard | Related Organizations');
      }
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'], {
          queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
        });
      } else {
        this.showLoading = true;
        this.message = '';

        this.route.queryParams.subscribe(
          communityId => {
            this.communityId = communityId['communityId'];

            if(!this.curatorAffiliations) {
              this.getAffiliations();
            }
            this.organizationsPageStatus();
          }
        );
      }
    });
  }

  getAffiliations() {
    this.affiliationService.initAffiliations(this.properties, this.properties.communityAPI + this.communityId + "/organizations");
    this.affiliationService.affiliations.subscribe(
      affiliations => {
        this.affiliations = affiliations;
        this.getOrganizationsPageId();
        //this.showLoading = false;
      },
      error => {
        console.error("Affiliations Component: Error getting affiliations for community with id: "+this.communityId, error);
        this.showLoading = false;
      }
    );
  }

  getOrganizationsPageId() {
    this._helpContentService.getPageByRoute("/organizations", this.properties.adminToolsAPIURL).subscribe(
      pages => {
        if(pages && pages[0]) {
          this.organizationsPageId = pages[0]._id;
        }
        this.showLoading = false;
      },
      error => {
        console.error("Affiliations Component: Error getting page with route '/organizations' for community with id: "+this.communityId, error);
        this.showLoading = false;
      }
    );
  }

  initAffiliation(affiliation: Affiliation = null) {
    this.resetMessages();

    if (affiliation) {
      this.affiliation = {...affiliation};
      if(!this.curatorAffiliations) {
        this.affiliation.communityId = affiliation.communityId;
        this.affiliation.id = affiliation.id;
      }
      if(this.curatorAffiliations) {
        this.affiliationModal.okButtonText = 'OK';
      } else {
        this.affiliationModal.okButtonText = 'Save Affiliation';
      }
    } else {
      this.index = -1;
      this.affiliation = new Affiliation();
      if(!this.curatorAffiliations) {
        this.affiliation.communityId = this.communityId;
      }
    }
    this.affiliationModal.okButtonLeft = false;
    if(this.curatorAffiliations) {
      this.affiliationModal.okButtonText = 'OK';
    } else {
      this.affiliationModal.okButtonText = 'Save Affiliation';
    }
    this.affiliationModal.open();
  }

  public chooseAffiliation(index: number, action: string = 'delete') {
    this.resetMessages();
    this.index = index;
    const affiliation: Affiliation = this.affiliations[index];
    if (action === 'delete') {
      this.removeAffiliationModal.message = 'Do you want to remove ' +
        affiliation.name +  ' from your Affiliations?';
      this.removeAffiliationModal.okButtonText = 'Yes';
      this.removeAffiliationModal.cancelButtonText = 'No';
      this.removeAffiliationModal.open();
    } else if (action === 'edit') {
      this.initAffiliation(affiliation);
    }
  }

  updateCommunityAffiliations(index: number) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams:
          {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      HelperFunctions.scroll();

        this.showLoading = true;

        this.affiliationService.updateAffiliation(this.properties.communityAPI + this.communityId + '/organizations',
          this.affiliation).subscribe((affiliation) => {
            if (affiliation) {
              if (index === -1) {
                this.affiliations.push(affiliation);
              } else {
                this.affiliations[index] = affiliation;
              }
              if(this.affiliation.id) {
                this.handleUpdateSuccess('Your organization has been updated successfully!');
              } else {
                this.handleUpdateSuccess('Your organization has been saved successfully!');
              }
            }
          },
          error => {
            if(this.affiliation.id) {
              this.handleUpdateError('Your organization could not be updated. Try again later!', error);
            } else {
              this.handleUpdateError('Organization could not be saved. Try again later!', error);
            }
          });
    }
  }

  addAffiliation() {
    if (!this.isEmptyAffiliation()) {
          if (!this.curatorAffiliations) {
            this.updateCommunityAffiliations(this.index);
          } else {
            if (this.index === -1) {
              this.affiliations.push(this.affiliation);
            } else {
              this.affiliations[this.index] = this.affiliation;
            }
          }
          this.change();
    }
  }

  removeAffiliation() {
    if(!this.curatorAffiliations) {
      HelperFunctions.scroll();

      this.showLoading = true;
      this.affiliationService.deleteAffiliation(this.properties.communityAPI + this.communityId + '/organizations',
        this.affiliations[this.index].id).subscribe((deleteOK) => {
          this.affiliations.splice(this.index, 1);
          this.handleUpdateSuccess('Organization has been deleted');
        },
        error => {
          this.handleUpdateError('Organization could not be deleted. Try again later!', error);
        }
      );
    } else {
      this.affiliations.splice(this.index, 1);
      this.change();
    }
  }

  private organizationsPageStatus() {
    this._helpContentService.getCommunityFull(this.communityId, this.properties.adminToolsAPIURL).subscribe((community) => {
      for(let page of community.pages) {
        if(page['route'] === '/organizations') {
          this.organizationsEnabled = page['isEnabled'];
          return;
        }
      }
      this.organizationsEnabled = false;
    })
  }

  private change() {
    this.hasChanged = true;
    if(this.curatorAffiliations) {
      this.affiliationsChange.emit(this.hasChanged);
    }
  }

  private resetMessages() {
    this.message = '';
    if(this.curatorAffiliations) {
      this.resetCuratorMessages.emit(true);
    }
  }

  handleUpdateError(message: string, error) {
    this.resetMessages();
    this.message = message;
    this.messageType = "warning";
    console.log('Server responded: ', error);

    this.showLoading = false;
  }

  handleUpdateSuccess(message) {
    this.resetMessages();
    this.message = message;
    this.messageType = "success";
    this.showLoading = false;
  }

  isEmptyAffiliation(): boolean {
    return ((!this.affiliation.name || this.affiliation.name === '') ||
      (!this.affiliation.logo_url || this.affiliation.logo_url === '') ||
      (!this.affiliation.website_url || this.affiliation.website_url === ''));
  }

  _format(name: string){
    if(name) {
      return (((name).length > this.maxCharacters) ? (name.substring(0, (this.maxCharacters - ('...').length)) + '...') : name);
    } else {
      return null;
    }
  }

}
