import {Component, ViewChild} from "@angular/core";
import {SearchUtilsClass} from "../../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {ErrorMessagesComponent} from "../../openaireLibrary/utils/errorMessages.component";
import {ErrorCodes} from "../../openaireLibrary/utils/properties/errorCodes";
import {EnvProperties} from "../../openaireLibrary/utils/properties/env-properties";
import {ActivatedRoute} from "@angular/router";
import {AdvancedField, Filter, Value} from "../../openaireLibrary/searchPages/searchUtils/searchHelperClasses.class";
import {SearchFields} from "../../openaireLibrary/utils/properties/searchFields";
import {CommunitiesService} from "../../openaireLibrary/connect/communities/communities.service";
import {Session, User} from "../../openaireLibrary/login/utils/helper.class";
import {CommunityInfo} from "../../openaireLibrary/connect/community/communityInfo";
import {StringUtils} from "../../openaireLibrary/utils/string-utils.class";
import {UserManagementService} from "../../openaireLibrary/services/user-management.service";
import {Breadcrumb} from "../../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {
  NewSearchPageComponent,
  SearchForm
} from "../../openaireLibrary/searchPages/searchUtils/newSearchPage.component";
import {properties} from "../../../environments/environment";
import {Subscriber} from "rxjs";

@Component({
  selector: 'search-communities',
  template: `
    <new-search-page pageTitle="Communities"
                     [hasPrefix]=true prefix="OpenAIRE Connect | "
                     [formPlaceholderText]="'Search OpenAIRE Communities'"
                     [type]="(results.length > 1)?'communities':'community'" entityType="community"
                     [results]="results" [searchUtils]="searchUtils"
                     [showResultCount]=true
                     [disableForms]="disableForms"
                     [showIndexInfo]=false
                     [simpleView]="true"
                     [searchForm]="searchForm"
                     [fieldIds]="fieldIds" [fieldIdsMap]="fieldIdsMap" [selectedFields]="selectedFields"
                     [simpleSearchLink]="searchLink" [entitiesSelection]="false" [showBreadcrumb]="true" [breadcrumbs]="breadcrumbs"
                     [basicMetaDescription]="['Research communities', 'Discover OpenAIRE research gateways for research communities.']">
    </new-search-page>
  `
})
export class SearchCommunitiesComponent {
  private errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;
  public results: CommunityInfo[] = [];
  public totalResults: CommunityInfo[];
  public subscriptions = [];
  public filters = [];
  public searchFields: SearchFields = new SearchFields();
  public searchUtils: SearchUtilsClass = new SearchUtilsClass();
  public selectedFields: AdvancedField[] = [];
  public disableForms: boolean = false;
  public baseUrl: string = null;
  public fieldIds: string[] = ["q"];
  public refineFields: string[] = this.searchFields.COMMUNITIES_SEARCH_FIELDS;
  public searchForm: SearchForm = {dark: false, class: 'search-form'};
  public fieldIdsMap = {
    ["q"]: {
      name: "All fields",
      type: "keyword",
      param: "q",
      operator: "op",
      equalityOperator: "=",
      filterType: null
    }
  };
  public keyword = "";
  public searchLink;
  public showType = false;
  public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'Communities'}];
  properties: EnvProperties;
  @ViewChild(NewSearchPageComponent, {static: true}) searchPage: NewSearchPageComponent;
  private user: User;
  
  constructor(private route: ActivatedRoute,
              private _communitiesService: CommunitiesService,
              private userManagementService: UserManagementService) {
    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
    this.searchUtils.status = this.errorCodes.LOADING;
  }
  
  public ngOnInit() {
    this.properties = properties;
    this.baseUrl = this.properties.searchLinkToCommunities;
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
      this.searchPage.resultsPerPage = 10;
      this.keyword = (params['fv0'] ? params['fv0'] : '');
      this.keyword = StringUtils.URIDecode(this.keyword);
      this.searchUtils.page = (params['page'] === undefined) ? 1 : +params['page'];
      this.searchUtils.sortBy = (params['sortBy'] === undefined) ? '' : params['sortBy'];
      this.searchUtils.validateSize(params['size']);
      this.searchUtils.baseUrl = this.baseUrl;
      this.searchPage.searchUtils = this.searchUtils;
      if (this.searchUtils.sortBy && this.searchUtils.sortBy != "creationdate,descending" && this.searchUtils.sortBy != "creationdate,ascending") {
        this.searchUtils.sortBy = "";
      }
      this.searchPage.refineFields = this.refineFields;
      this.searchLink = this.properties.searchLinkToCommunities;
      this.selectedFields = [];
      this.searchPage.prepareSearchPage(this.fieldIds, this.selectedFields, this.refineFields, [], this.fieldIdsMap, null, params, "community", null);
      
      let queryParams = params;
      if (typeof document !== 'undefined') {
        this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
          this.user = user;
          this.initCommunities(queryParams);
        }));
      } else {
        this.initCommunities(queryParams);
      }
    }));
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  
  private parseResults(data: any) {
    for (let i = 0; i < data.length; i++) {
      this.totalResults[i] = data[i];
      this.totalResults[i].isManager = this.isCommunityManager(this.totalResults[i]);
      this.totalResults[i].isSubscribed = Session.isSubscribedTo('community', this.totalResults[i].communityId, this.user);
    }
  }
  
  /**
   * Initialize communities from Communities APIs
   *
   * @param params
   */
  private initCommunities(params) {
    if(this.totalResults) {
      this.parseResults(this.totalResults);
      this._getResults(params);
    } else {
      this.subscriptions.push(this._communitiesService.getCommunitiesState().subscribe(
        data => {
          this.totalResults = [];
          this.parseResults(data);
          this._getResults(params);
        },
        err => {
          this.handleError('Error getting communities', err);
          this.searchUtils.status = this.errorMessages.getErrorCode(err.status);
          this.disableForms = false;
        }
      ));
    }
  }
  
  
  /**
   * Get all communities from Communities API and apply permission access validator,
   * keyword searching, filter, paging and sorting.
   *
   * @param params, status
   * @private
   */
  private _getResults(params) {
    this.searchUtils.status = this.errorCodes.LOADING;
    this.disableForms = true;
    this.results = this.totalResults;
    this.filters = this.createFilters();
    this.searchUtils.totalResults = 0;
    this.applyParams(params);
  }
  
  /**
   * Return the communities in which user has permission to view or manage.
   */
  private showCommunities() {
    let ret: CommunityInfo[] = [];
    for (let result of this.results) {
      if (result.isPrivate() && result.isManager) {
        ret.push(result);
      } else if (result.isRestricted() || result.isPublic()) {
        ret.push(result);
      }
    }
    this.results = ret;
  }
  
  /**
   * Apply permission access validator,
   * keyword searching, filter, paging and sorting.
   *
   * @param params
   */
  public applyParams(params: Map<string, string>) {
    this.showCommunities();
    if (this.keyword && this.keyword != '') {
      this.searchForKeywords();
    }
    this.checkFilters(params);
    this.sort();
    this.searchUtils.totalResults = this.results.length;
    this.filters = this.searchPage.prepareFiltersToShow(this.filters, this.searchUtils.totalResults);
    this.results = this.results.slice((this.searchUtils.page - 1) * this.searchUtils.size, (this.searchUtils.page * this.searchUtils.size));
    this.searchUtils.status = this.errorCodes.DONE;
    if (this.searchUtils.totalResults == 0) {
      this.searchUtils.status = this.errorCodes.NONE;
    }
    this.disableForms = false;
    if (this.searchUtils.status == this.errorCodes.DONE) {
      // Page out of limit!!!
      let totalPages: any = this.searchUtils.totalResults / (this.searchUtils.size);
      if (!(Number.isInteger(totalPages))) {
        totalPages = (parseInt(totalPages, 10) + 1);
      }
      if (totalPages < this.searchUtils.page) {
        this.searchUtils.totalResults = 0;
        this.searchUtils.status = this.errorCodes.OUT_OF_BOUND;
      }
    }
  }
  
  
  /**
   * Parse the given keywords into array and check if any of the requirements field of a community includes
   * one of the given words.
   */
  private searchForKeywords() {
    let ret: CommunityInfo[] = [];
    let keywords: string[] = this.keyword.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
    for (let i = 0; i < this.results.length; i++) {
      for (let keyword of keywords) {
        keyword = keyword.toLowerCase();
        if (keyword != '' && (StringUtils.containsWord(this.results[i].title, keyword) || StringUtils.containsWord(this.results[i].shortTitle, keyword) ||
          StringUtils.containsWord(this.results[i].communityId, keyword) || StringUtils.containsWord(this.results[i].description, keyword))) {
          ret.push(this.results[i]);
          break;
        }
      }
    }
    this.results = ret;
  }
  
  /**
   * Check the current results if they satisfy the values of each filter category and
   * update the number of possible results in each value.
   *
   * @param params
   */
  private checkFilters(params) {
    let typeResults: CommunityInfo[] = this.applyFilter('type', params);
    let accessResults: CommunityInfo[] = this.applyFilter('access', params);
    let roleResults: CommunityInfo[] = this.results;
    if (this.user) {
      roleResults = this.applyFilter('role', params);
      this.resetFilterNumbers('role');
      this.updateFilterNumbers(accessResults.filter(value => {
        return typeResults.includes(value);
      }), 'role');
    }
    this.resetFilterNumbers('access');
    this.updateFilterNumbers(typeResults.filter(value => {
      return roleResults.includes(value);
    }), 'access');
    this.resetFilterNumbers('type');
    this.updateFilterNumbers(accessResults.filter(value => {
      return roleResults.includes(value);
    }), 'type');
    this.results = accessResults.filter(value => {
      return typeResults.includes(value);
    })
    this.results = this.results.filter(value => {
      return roleResults.includes(value);
    });
  }
  
  /**
   * Apply filter with filterId and return the results
   *
   * @param filterId
   * @param params
   */
  private applyFilter(filterId: string, params): CommunityInfo[] {
    let results: CommunityInfo[] = [];
    let values: string[] = [];
    if (params[filterId]) {
      values = (StringUtils.URIDecode(params[filterId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
    }
    console.log(filterId + ": " +values)
    if (filterId == 'type') {
      for (let i = 0; i < this.results.length; i++) {
        if (values.length == 0) {
          results.push(this.results[i]);
        } else {
          for (let value of values) {
            if (this.results[i].type == value.replace(/["']/g, "")) {
              results.push(this.results[i]);
              break;
            }
          }
        }
      }
    } else if (filterId == 'access') {
      for (let i = 0; i < this.results.length; i++) {
        if (values.length == 0) {
          results.push(this.results[i]);
        } else {
          // console.log(this.results[i].status, this.results[i].isPublic(),this.results[i].isRestricted(), this.results[i].isPrivate() )
          for (let value of values) {
            if (value.replace(/["']/g, "") == 'public') {
              if (this.results[i].isPublic()) {
                results.push(this.results[i]);
                break;
              }
            } else if (value.replace(/["']/g, "") == 'restricted') {
              if (this.results[i].isRestricted()) {
                results.push(this.results[i]);
                break;
              }
            } else if (value.replace(/["']/g, "") == 'private') {
              if (this.results[i].isPrivate()) {
                results.push(this.results[i]);
                break;
              }
            }
          }
        }
      }
    } else if (filterId == 'role') {
      for (let i = 0; i < this.results.length; i++) {
        if (values.length == 0) {
          results.push(this.results[i]);
        } else {
          for (let value of values) {
            if (value.replace(/["']/g, "") == 'manager') {
              if (this.results[i].isManager) {
                results.push(this.results[i]);
                break;
              }
            }
            if (value.replace(/["']/g, "") == 'member') {
              if (this.results[i].isSubscribed) {
                results.push(this.results[i]);
                break;
              }
            }
          }
        }
      }
    }
    return results;
  }
  
  /**
   * Reset the values of filter with id filterId with zero.
   *
   * @param filterId
   */
  private resetFilterNumbers(filterId: string) {
    for (let i = 0; i < this.filters.length; i++) {
      if (this.filters[i].filterId == filterId) {
        for (let j = 0; j < this.filters[i].values.length; j++) {
          this.filters[i].values[j].number = 0;
        }
        break;
      }
    }
  }
  
  /**
   * Update the values of filter with id filterId based on
   * results.
   *
   * @param results
   * @param filterId
   */
  private updateFilterNumbers(results: CommunityInfo[], filterId: string) {
    for (let k = 0; k < results.length; k++) {
      for (let i = 0; i < this.filters.length; i++) {
        if (this.filters[i].filterId == filterId) {
          if (this.filters[i].filterId == 'type') {
            for (let j = 0; j < this.filters[i].values.length; j++) {
              if (results[k].type == this.filters[i].values[j].id) {
                this.filters[i].values[j].number++;
              }
            }
          } else if (this.filters[i].filterId == 'access') {
            if (results[k].isPublic()) {
              this.filters[i].values[0].number++;
            } else if (results[k].isRestricted()) {
              this.filters[i].values[1].number++;
            } else if (this.user) {
              this.filters[i].values[2].number++;
            }
          } else if (this.filters[i].filterId == 'role') {
            if (results[k].isManager) {
              this.filters[i].values[0].number++;
            }
            if (results[k].isSubscribed) {
              this.filters[i].values[1].number++;
            }
          }
          break;
        }
      }
    }
  }
  
  /**
   * Sorting results based on sortBy.
   */
  private sort() {
    if (this.searchUtils.sortBy == '') {
      this.results.sort((left, right): number => {
        if (left.title > right.title) {
          return 1;
        } else if (left.title < right.title) {
          return -1;
        } else {
          return 0;
        }
      })
    } else if (this.searchUtils.sortBy == 'creationdate,descending') {
      this.results.sort((left, right): number => {
        if (!right.date || left.date > right.date) {
          return -1;
        } else if (!left.date || left.date < right.date) {
          return 1;
        } else {
          return 0;
        }
      })
    } else if (this.searchUtils.sortBy == 'creationdate,ascending') {
      this.results.sort((left, right): number => {
        if (!right.date || left.date > right.date) {
          return 1;
        } else if (!left.date || left.date < right.date) {
          return -1;
        } else {
          return 0;
        }
      })
    }
  }
  
  
  private isCommunityManager(community: CommunityInfo): boolean {
    return Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || Session.isManager('community', community.communityId, this.user);
  }
  
  /**
   * Create Search Communities filters.
   *
   */
  private createFilters(): Filter[] {
    let filter_names = [];
    let filter_ids = [];
    let searchFields = new SearchFields();
    let filter_original_ids = searchFields.COMMUNITIES_SEARCH_FIELDS;
    let value_names = [];
    let value_original_ids = [];
    this.showType = this.results.filter(community => community.type === 'ri').length > 0;
    if (this.showType) {
      filter_names.push("Type");
      filter_ids.push("type");
      value_names.push(["Research Communities", "Research Initiatives"]);
      value_original_ids.push(["community", "ri"]);
    } else {
      filter_original_ids = searchFields.COMMUNITIES_SEARCH_FIELDS.splice(0, 1);
    }
    filter_names.push("Accessibility");
    filter_ids.push("access");
    if (!this.user) {
      value_names.push(["Public", "Restricted"]);
      value_original_ids.push(["public", "restricted"]);
    } else {
      value_names.push(["Public", "Restricted", "Private"]);
      value_original_ids.push(["public", "restricted", "private"]);
      filter_names.push("Role");
      filter_ids.push("role");
      value_names.push(["Manager", "Member"]);
      value_original_ids.push(["manager", "member"]);
    }
    let filters: Filter[] = [];
    for (let i = 0; i < filter_names.length; i++) {
      let values: Value[] = [];
      for (let j = 0; j < value_names[i].length; j++) {
        let value: Value = {name: value_names[i][j], id: value_original_ids[i][j], number: 0, selected: false};
        values.push(value);
      }
      let filter: Filter = {
        title: filter_names[i],
        filterId: filter_ids[i],
        originalFilterId: filter_original_ids[i],
        values: values,
        countSelectedValues: 0,
        "filterOperator": 'or',
        valueIsExact: true,
        filterType: "checkbox"
      };
      filters.push(filter);
    }
    return filters;
  }
  
  private handleError(message: string, error) {
    console.error('Communities Search Page: ' + message, error);
  }
  
}
