import {Component, OnInit} from "@angular/core";
import {StakeholderBaseComponent} from "../openaireLibrary/monitor-admin/utils/stakeholder-base.component";
import {ActivatedRoute, Router} from "@angular/router";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {PiwikService} from "../openaireLibrary/utils/piwik/piwik.service";
import {Meta, Title} from "@angular/platform-browser";
import {Stakeholder} from "../openaireLibrary/monitor/entities/stakeholder";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {CustomFilterService} from "../openaireLibrary/shared/customFilter.service";
import {LinksResolver} from "../search/links-resolver";
import {SearchCustomFilter} from "../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {LayoutService} from "../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {OpenaireEntities} from "../openaireLibrary/utils/properties/searchFields";
import {SearchDataprovidersService} from "../openaireLibrary/services/searchDataproviders.service";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {ConfigurationService} from "../openaireLibrary/utils/configuration/configuration.service";
import {Irish} from "../shared/irish";

@Component({
  selector: 'repository',
  template: `
      <loading *ngIf="loading" class="uk-position-center"></loading>
      <div *ngIf="!loading">
        <div class="uk-banner uk-light">
          <div class="uk-container uk-container-large">
            <div class="uk-padding-small uk-padding-remove-vertical">
              <div *ngIf="stakeholder" class="uk-grid uk-grid-large uk-flex-middle uk-margin-medium-bottom" uk-grid>
                <div class="uk-width-expand">
                  <div class="uk-grid uk-grid-small uk-flex-middle" uk-grid>
                    <div class="uk-card uk-card-default uk-padding-small">
                      <img *ngIf="stakeholder.logoUrl; else elseBlock" [src]="stakeholder | logoUrl" [alt]="stakeholder.name + ' logo'" class="uk-height-max-xsmall" style="max-width: 180px;">
                      <ng-template #elseBlock>
                        <img src="assets/common-assets/placeholder.png" alt="OpenAIRE placeholder logo" class="uk-height-max-xsmall" style="max-width: 180px;">
                      </ng-template>
                    </div>
                    <div class="uk-width-expand uk-margin-small-left">
                      <div class="uk-h4 uk-margin-remove uk-text-truncate">{{stakeholder.name}}</div>
                      <ng-container *ngIf="stakeholder.details">
                        <div class="uk-text-xsmall uk-margin-small-bottom">
                          <entity-metadata [entityType]="stakeholder.details.type"
                                        [compatibilityString]="stakeholder.details.compatibility" 
                                        [organizations]="stakeholder.details.organizations">
                          </entity-metadata>
                        </div>
                        <div class="uk-text-small">
                          <!-- Website URL -->
                          <div *ngIf="stakeholder.details.websiteURL && stakeholder.details.websiteURL != ''" class="uk-margin-xsmall-bottom">
                            <span>Website URL: </span>
                            <span class="uk-text-italic">
                              <a href="{{stakeholder.details.websiteURL}}" target="_blank" class="custom-external">
                                {{stakeholder.details.websiteURL}}
                              </a>
                            </span>
                          </div>
                          <!-- OAI-PMH URL-->
                          <div *ngIf="stakeholder.details.OAIPMHURL && stakeholder.details.OAIPMHURL != ''" class="uk-margin-xsmall-bottom">
                            <span>OAI-PMH URL: </span>
                            <span class="uk-text-italic">
                              <a href="{{stakeholder.details.OAIPMHURL}}" target="_blank" class="custom-external">
                                {{stakeholder.details.OAIPMHURL}}
                              </a>
                            </span>
                          </div>
                        </div>
                      </ng-container>
                    </div>
                  </div>
                </div>
              </div>
              <h1 *ngIf="!stakeholder" class="uk-h3 uk-margin-small-bottom">{{entities.datasources}}</h1>
            </div>
          </div>
          <div *ngIf="stakeholder" class="uk-banner-footer">
            <div class="uk-container uk-container-large uk-flex uk-flex-between">
              <ul class="uk-banner-tab uk-padding-small uk-padding-remove-vertical">
                <li [class.uk-active]="!isSearch">
                  <a [routerLink]="['./', stakeholder.alias]" [relativeTo]="_route" (click)="isSearch = false">
                    {{entities.stakeholder}}
                  </a>
                </li>
                <li [class.uk-active]="isSearch">
                  <a [routerLink]="['./', stakeholder.alias, 'search']" [queryParams]="routerHelper.createQueryParams(['type','peerreviewed'], [quote('publications'), quote('true')])" [relativeTo]="_route">
                    Browse {{openaireEntities.RESULTS}}
                  </a>
                </li>
              </ul>
              <a *ngIf="isProvideManager" [href]="provideLink" target="_blank" class="uk-button uk-margin-large-right uk-flex uk-flex-middle">
                <span class="uk-margin-small-right">Manage at</span> 
                <img class="uk-margin-xsmall-bottom" width="78" src="assets/common-assets/logo-small-provide.png">
                <icon name="east" flex="true" class="uk-margin-small-left"></icon>
              </a>
            </div>
          </div>
        </div>
        <div *ngIf="!this.alias || this.stakeholder" class="uk-margin-medium-top uk-margin-medium-bottom">
          <router-outlet></router-outlet>
        </div>
        <role-verification *ngIf="stakeholder" [id]="stakeholder.alias" [name]="stakeholder.name" [type]="stakeholder.type" [service]="'irish'" [relativeTo]="null"></role-verification>
      </div>
  `
})
export class RepositoryComponent extends StakeholderBaseComponent implements OnInit {
  stakeholder: Stakeholder;
  alias: string;
  isSearch: boolean = false;
  loading: boolean = false;
  openaireEntities = OpenaireEntities;
  isProvideManager: boolean;

  constructor(private stakeholderService: StakeholderService,
              private userManagementService: UserManagementService,
              private searchDataprovidersService: SearchDataprovidersService,
              private layoutService: LayoutService,
              private _customFilterService: CustomFilterService,
              protected _router: Router,
              protected _route: ActivatedRoute,
              protected seoService: SEOService,
              protected _piwikService: PiwikService,
              protected _title: Title,
              protected _meta: Meta,
              private configurationService: ConfigurationService) {
    super();
    super.initRouterParams(this._route, event => {
      this.isSearch = event.url.includes('/search');
    });
  }

  ngOnInit() {
    this.layoutService.setRootClass('datasource');
    this.title = 'Repository Monitors';
    this.description = 'Repository Monitors';
    this.setMetadata();
    this.params.subscribe(params => {
      this.alias = params['stakeholder'];
      if (this.alias) {
        if(this.stakeholder?.alias !== this.alias) {
          this._customFilterService.setCustomFilter(null);
          this.loading = true;
          this.subscriptions.push(this.stakeholderService.getStakeholder(this.alias, true).subscribe(stakeholder => {
            this.stakeholder = stakeholder;
            if (this.stakeholder && this.stakeholder.type === 'datasource') {
              this.setProperties(this.stakeholder.alias, this.stakeholder.type, this.configurationService);
              LinksResolver.resetProperties();
              LinksResolver.setSearchAndResultLanding("repository/" + this.stakeholder.alias);
              this._customFilterService.setCustomFilter(
                  [new SearchCustomFilter("National", "country", "IE", "Irish National Monitor", false),
                    new SearchCustomFilter("Repository", "resulthostingdatasourceid", this.stakeholder.index_id, this.stakeholder.index_name, true)
                    // new SearchCustomFilter("Repository", "collectedfromdatasourceid", this.stakeholder.index_id, this.stakeholder.index_name, true)
                  ]);
              this.subscriptions.push(this.searchDataprovidersService.searchDataproviderById(this.stakeholder.index_id).subscribe(data => {
                this.stakeholder.details = data[0];
                this.subscriptions.push(this.userManagementService.getUserInfoAt(1).subscribe(user => {
                  this.isProvideManager = !!user.role.find(role => role.includes(this.stakeholder.details.originalId.toUpperCase()));
                }));
                this.loading = false;
              }));
            } else {
              this.navigateToError();
            }
          }));
        }
      } else {
        this.stakeholder = null;
        this._customFilterService.setCustomFilter(null);
      }
    });
  }

  get provideLink() {
    if(this.stakeholder?.details?.originalId) {
      return 'https://' + (this.properties.environment != 'production'?'beta.':'') + 'provide.openaire.eu/repository/' + this.stakeholder.details.originalId + '/dashboard';
    } else {
      return null;
    }
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    this.layoutService.setRootClass(null);
    this.setProperties(Irish.irishAdminToolsCommunity, Irish.irishAdminToolsPortalType, this.configurationService);
  }
}
