import { Component, ViewChild, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';

import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass } from '../../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {ManageCommunityProjectsService} from '../../../services/manageProjects.service';
import {SearchCommunityProjectsService} from '../../../openaireLibrary/connect/projects/searchProjects.service';
import {RouterHelper} from '../../../openaireLibrary/utils/routerHelper.class';
import {DOI, StringUtils} from '../../../openaireLibrary/utils/string-utils.class';

import {Session} from '../../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';

@Component({
    selector: 'remove-projects',
    templateUrl: './remove-projects.component.html',
    styles: [`
      #dpTable_info, #dpTable_paginate,  #dpTable_length,  #dpTable_filter{
        display: none;
      }

      `],
    encapsulation: ViewEncapsulation.None // this used in order styles to work
})

export class RemoveProjectsComponent implements OnInit {
  public routerHelper:RouterHelper = new RouterHelper();

  private community: string = '';
  private communityUrl = "https://beta.explore.openaire.eu";

  public errorCodes: ErrorCodes;

  @Output() communityProjectsChanged  = new EventEmitter();
  public communityProjects = [];
  public communitySearchUtils:SearchUtilsClass = new SearchUtilsClass();

  public sub: any; public subResults: any; subRemove: any;
  properties:EnvProperties;

  public disableForms: boolean = false;

  dtOptions: DataTables.Settings = {};
  showTable = false; filteringAdded = false;
  @ViewChild(DataTableDirective) datatableElement: DataTableDirective;
  dtTrigger: Subject<any> = new Subject(); //necessary

  public rowsOnPage:number  = 10;

  public queryParameters: string = "";

  public query = '';
  public selectedProjects=[] ;
  public elementRef;

  public funders:Set<string>;
  public selectedFunder:string ="";
  //@Output() projectSelected = new EventEmitter();
  //@Input() public properties:EnvProperties;

  public projects:string[];
  private triggered: boolean = false;

  private selectedCommunityProject: any;

  @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;

  ngOnInit() {
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
        this.properties = data.envSpecific;
      });

    this.route.queryParams.subscribe(params => {
      if(params['communityId']) {
        this.community = params['communityId'];
        this.communityUrl = "https://beta."+this.community+".openaire.eu";

        this._getCommunityProjects();
        //this.getFunders();
        //this._getOpenaireProjects("", 1, 10);
      }
    });

    this.dtOptions = {
      // "paging": true,
      // "searching": true,
      // "lengthChange": false,
      "pageLength": this.rowsOnPage,
      "language": {
          "search": "",
          "searchPlaceholder": "Search projects..."
        }
    };

    this.communitySearchUtils.keyword = "";
  }

  constructor(private route: ActivatedRoute, private _router: Router, private _manageCommunityProjectsService: ManageCommunityProjectsService, private _searchCommunityProjectsService: SearchCommunityProjectsService) {
    this.errorCodes = new ErrorCodes();
    this.communitySearchUtils.status = this.errorCodes.LOADING;
  }

  public ngOnDestroy() {
    if(this.sub){
      this.sub.unsubscribe();
    }
    if(this.subResults){
      this.subResults.unsubscribe();
    }
    if(this.subRemove){
      this.subRemove.unsubscribe();
    }

    $.fn['dataTable'].ext.search.pop();
  }

  rerender(): void {
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // Destroy the table first
      dtInstance.destroy();

      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

  ngAfterViewInit(): void {
    $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {

       if (this.filterData(data, this.communitySearchUtils.keyword, this.selectedFunder)) {
         return true;
       }
       return false;
     });

     //console.info("ngAfterViewInit");
  }

  filterData(row: any, query: string, selectedFunder: string) {
    let returnValue: boolean = false;

    if(query) {
      for(var i=0; i <3; i++){
        var r= this.filterQuery(row[i], query);
        if(r) {
          returnValue = true;
          break;
        }
      }

      if(!returnValue) {
        return false;
      }
    }

    if(selectedFunder){
      return this.filterQuery(row[2], selectedFunder);
    }

    return true;
  }

  filterQuery(data, query){
    if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
      return true;
    }else{
      return false;
    }
  }


  /*
  Trigger a table draw in order to get the initial filtering
  */
  triggerInitialLoad(){
    this.triggered = true;
    //console.info("triggerInitialLoad");
    setTimeout(function(){
      var table = (<any>$('#dpTable')).DataTable();
      table.page( 0  ).draw( false );
    }, 500);
    this.dtTrigger.next();
  }

  public inCommunity(result: any): any {
    let found = false;
    for(let project of this.communityProjects) {
      if(project.opeaireId == result.id) {
        return true;
      } else if(result['title'].name.search("("+project.grantId+")") != -1 && result.funderShortname == project.funder) {
        return true;
      }
    }
    return found;

  }

  goTo(page:number = 1){
      this.communitySearchUtils.page=page;

      var table = $('#dpTable').DataTable();
      table.page( page - 1  ).draw( false );

      var info = table.page.info();
      this.communitySearchUtils.totalResults = info.recordsDisplay;
  }

  totalPages(): number {
      let totalPages:any = this.communitySearchUtils.totalResults/(this.rowsOnPage);
      if(!(Number.isInteger(totalPages))) {
          totalPages = (parseInt(totalPages, 10) + 1);
      }
      return totalPages;
  }

  public confirmedDeleteProject(data : any) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.subRemove = this._manageCommunityProjectsService.removeProject(this.properties, this.community, this.selectedCommunityProject.id).subscribe(
        data => {
          //console.info(data);
        },
        err => {
          console.log(err);
        },
        () => {
          let index = this.communityProjects.indexOf(this.selectedCommunityProject);
          this.communityProjects.splice(index, 1);

          this.communitySearchUtils.totalResults--;
          this.communitySearchUtils.page=1;

          this.rerender();
        }
      )
    }
  }

  public removeProject(communityProject: any) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.selectedCommunityProject = communityProject;
      this.alertModalDeleteCommunity.cancelButton = true;
      this.alertModalDeleteCommunity.okButton = true;
      this.alertModalDeleteCommunity.alertTitle = "Remove project?";
      let title = "";
      if(communityProject.name) {
        title = communityProject.name;
      }
      if(communityProject.name && communityProject.acronym) {
        title += " (";
      }
      if(communityProject.acronym) {
        title += communityProject.acronym;
      }
      if(communityProject.name && communityProject.acronym) {
        title += ")";
      }
      this.alertModalDeleteCommunity.message = "Project";
      if(title) {
        this.alertModalDeleteCommunity.message += " '"+title+"' ";
      }
      this.alertModalDeleteCommunity.message += "will be removed from your community. Are you sure?";
      this.alertModalDeleteCommunity.okButtonText = "Yes";
      this.alertModalDeleteCommunity.open();
    }
  }

  public _getCommunityProjects(){
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.communitySearchUtils.status = this.errorCodes.LOADING;
      this.disableForms = true;
      this.communityProjects = [];
      this.communitySearchUtils.totalResults = 0;
      this.communitySearchUtils.page=1;
      this.communitySearchUtils.keyword = "";
      this.selectedFunder = "";

      this.subResults = this._searchCommunityProjectsService.searchProjects(this.properties, this.community).subscribe(
          data => {
            //console.info("search Projects [total communityProjects:"+data.length+"]");
            this.communityProjects = data;

            this.communitySearchUtils.totalResults = data.length;
            this.communitySearchUtils.status = this.errorCodes.DONE;
            // if(this.communitySearchUtils.totalResults == 0 ){
            //   this.communitySearchUtils.status = this.errorCodes.NONE;
            // }
            this.disableForms = false;
            if(!this.triggered) {
              this.triggerInitialLoad();
            } else {
              var table = $('#dpTable').DataTable();
              table.clear();

              this.rerender();
            }

            this.communityProjectsChanged.emit({
                value: this.communityProjects,
            });

            this.createFunderFilter();
          },
          err => {
            console.log(err);
             //TODO check erros (service not available, bad request)

            if(err.status == '404') {
              this.communitySearchUtils.status = this.errorCodes.NOT_FOUND;
            } else if(err.status == '500') {
              this.communitySearchUtils.status = this.errorCodes.ERROR;
            } else {
              this.communitySearchUtils.status = this.errorCodes.NOT_AVAILABLE;
            }

            this.disableForms = false;
            if(!this.triggered) {
              this.triggerInitialLoad();
            } else {
              var table = $('#dpTable').DataTable();
              table.clear();

              this.rerender();
            }
          }
      );
    }
  }

  private createFunderFilter(): Set<String> {
    this.funders = new Set<string>();
    let i;
    for(i=0; i<this.communityProjects.length; i++) {
      let funder = this.communityProjects[i].funder;
      if(funder && !this.funders.has(funder)) {
        this.funders.add(funder);
      }
    }
    return this.funders;
  }
}
