import {ChangeDetectorRef, Component} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder} from "@angular/forms";
import {BrowseStakeholderBaseComponent} from "../../shared/browse-stakeholder-base.component";
import {LayoutService} from "../../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
import {SearchDataprovidersService} from "../../openaireLibrary/services/searchDataproviders.service";
import {SearchResult} from "../../openaireLibrary/utils/entities/searchResult";
import {ResultPreview} from "../../openaireLibrary/utils/result-preview/result-preview";
import {forkJoin, Observable, of} from "rxjs";
import {catchError} from "rxjs/operators";
import {StakeholderPublication} from "../../shared/irish";
import {IrishMonitorService} from "../../shared/irish-monitor.service";

@Component({
  selector: 'browse-repository',
  templateUrl: 'browse-repositories.component.html'
})
export class BrowseRepositoriesComponent extends BrowseStakeholderBaseComponent {
  sortBy = 'alphAsc';
  sortOptions: Option[] = [
    {value: 'alphAsc', label: 'Alphabetically Asc. (A-Z)'},
    {value: 'alphDsc', label: 'Alphabetically Dsc. (Z-A)'}
  ]
  
  constructor(protected _route: ActivatedRoute,
              protected _router: Router,
              protected irishMonitorService: IrishMonitorService,
              protected layoutService: LayoutService,
              protected cdr: ChangeDetectorRef,
              protected fb: FormBuilder,
              private searchDataprovidersService: SearchDataprovidersService) {
    super();
  }

  sortByChanged() {
    switch(this.sortBy) {
      case 'alphAsc':
        // name or index_name ?
        this.stakeholders = this.stakeholders.sort((a, b) => a['index_name'].localeCompare(b['index_name']));
        this.afterStakeholdersInitialized();
        break;
      case 'alphDsc':
        this.stakeholders = this.stakeholders.sort((a, b) => b['index_name'].localeCompare(a['index_name']));
        this.afterStakeholdersInitialized();
        break;
      default:
        break;
    }
  }

  afterStakeholdersInitialized() {
    let currentFilteredStakeholders = this.filteredStakeholders.slice((this.currentPage-1)*this.pageSize, this.currentPage*this.pageSize);
    if(currentFilteredStakeholders && currentFilteredStakeholders.length > 0) {
      let obs: Observable<any>[] = [];
      currentFilteredStakeholders.forEach(item => {
        if (!item.details) {
          this.showLoading = true;
          let ob = this.searchDataprovidersService.searchDataproviderById(item.index_id).pipe(
            catchError(error => {
              let details: SearchResult = new SearchResult();
              details['title'] = {'name': item.name, 'accessMode': ''};
              details['entityType'] = "dataprovider";
              return of([details]);
            }));
          obs.push(ob);
        }
      });
      this.subscriptions.push(forkJoin(obs).subscribe(
        data => {
          data.forEach((item, index) => {
            currentFilteredStakeholders[index].details = item[0];
            currentFilteredStakeholders[index].details['title']['name'] = currentFilteredStakeholders[index].name;
          });
          this.showLoading = false;
        }
      ));
    } else {
      this.showLoading = false;
    }
  }

  public getResultPreview(result: SearchResult): ResultPreview {
    return ResultPreview.searchResultConvert(result, (result.entityType) ? result.entityType : this.typeAsLabel);
  }
}

export class StakeholderRepository extends StakeholderPublication {
  details: any;
}
