import { Component, ViewChild, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
//import { Subject } from 'rxjs/Subject';
import {SearchResult}     from '../../../openaireLibrary/utils/entities/searchResult';
import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
import {SearchFields, FieldDetails} from '../../../openaireLibrary/utils/properties/searchFields';
import {SearchUtilsClass } from '../../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {SearchProjectsService} from '../../../openaireLibrary/services/searchProjects.service';
import {RouterHelper} from '../../../openaireLibrary/utils/routerHelper.class';
import {DOI, StringUtils} from '../../../openaireLibrary/utils/string-utils.class';
import {ManageCommunityProjectsService} from '../../../services/manageProjects.service';

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

@Component({
    selector: 'add-projects',
    templateUrl: './add-projects.component.html',
})

export class AddProjectsComponent implements OnInit {
  @Input() communityProjects = [];
  //@Output() communityProjectsChanged  = new EventEmitter();

  private community: string = '';

  public openaireProjects = [];
  public undo = {};
  public queryParameters: string = "";

  public funders:string[];
  public selectedFunderId:string ="0";
  selectedFunderName:string ="Select funder:";

  public disableForms: boolean = false;

  public warningMessage = "";
  public infoMessage = "";

  public rowsOnPage:number  = 10;

  public routerHelper:RouterHelper = new RouterHelper();
  public errorCodes: ErrorCodes;
  public openaireSearchUtils:SearchUtilsClass = new SearchUtilsClass();
  public properties:EnvProperties = null;
  public pagingLimit:number = 0;
  public resultsPerPage: number = 0;

  public subFunders: any; public subResults: any; subAdd: any; subRemove: any;
  public body:string = "Send from page";

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

           this.route.queryParams.subscribe(params => {
             this.community = params['communityId'];
             this.getFunders();
             this._getOpenaireProjects("", 1, 10);

             var referrer = null;
             if (typeof location !== 'undefined') {
               referrer = location.href;
             }
             this.body = "[Please write your message here]";
             this.body = StringUtils.URIEncode(this.body);
           });
        });
  }

  constructor(private route: ActivatedRoute, private _router: Router, private _searchProjectsService: SearchProjectsService, private _manageCommunityProjectsService: ManageCommunityProjectsService) {
    this.errorCodes = new ErrorCodes();
    this.openaireSearchUtils.status = this.errorCodes.LOADING;
  }

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

  public addProject(project: SearchResult) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.subAdd = this._manageCommunityProjectsService.addProject(this.properties, this.community, project).subscribe(
        data => {
          this.undo[project.id] = data.id;
        },
        err => {
          console.log(err.status);
        }/*,
        () => {
          console.info("completed ADD");
        }*/
      );
    }
  }

  public removeProject(projectId: string, communityProjectId: string) {
    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, projectId).subscribe(
        data => {
          //console.info(data);
        },
        err => {
          console.log(err);
        },
        () => {
          this.undo[communityProjectId] = "";
        }
      )
    }
  }

  public inCommunity(project: any): any {
    for(let communityProject of this.communityProjects) {
      if(communityProject.openaireId == project.id) {
        return true;
      } else if(project.code == communityProject.grantId && project.funderShortname == communityProject.funder) {
        return true;
      }
    }

    if(this.undo[project.id]) {
      return true;
    }
    return false;
  }

  getFunders ()  {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.subFunders = this._searchProjectsService.getFunders(this.properties).subscribe(
        data => {
          this.funders = data[1];
        },
        err => console.log(err)
      );
    }
  }

  private _getOpenaireProjects(parameters:string, page: number, size: number){
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      if(page > this.pagingLimit) {
        size=0;
      }

      if(this.openaireSearchUtils.status == this.errorCodes.LOADING) {
        this.openaireSearchUtils.status = this.errorCodes.LOADING;

        this.disableForms = true;
        this.openaireProjects = [];
        this.openaireSearchUtils.totalResults = 0;

        this.subResults = this._searchProjectsService.searchProjects(parameters, null, page, size, [], this.properties).subscribe(
          data => {
              this.undo = {};
              //console.info("total openaire projects = "+data[0]);
              this.openaireSearchUtils.totalResults = data[0];
              this.openaireProjects = data[1];

              //this.searchPage.checkSelectedFilters(this.filters);

              this.openaireSearchUtils.status = this.errorCodes.DONE;
              if(this.openaireSearchUtils.totalResults == 0 ){
                this.openaireSearchUtils.status = this.errorCodes.NONE;
              }

              this.disableForms = false;

              if(this.openaireSearchUtils.status == this.errorCodes.DONE) {
                // Page out of limit!!!
                let totalPages:any = this.openaireSearchUtils.totalResults/(this.openaireSearchUtils.size);
                if(!(Number.isInteger(totalPages))) {
                    totalPages = (parseInt(totalPages, 10) + 1);
                }
                if(totalPages < page) {
                  this.openaireSearchUtils.totalResults = 0;
                  this.openaireSearchUtils.status = this.errorCodes.OUT_OF_BOUND;
                }
              }
          },
          err => {
              console.log(err);
               //TODO check erros (service not available, bad request)
              if(err.status == '404') {
                this.openaireSearchUtils.status = this.errorCodes.NOT_FOUND;
              } else if(err.status == '500') {
                this.openaireSearchUtils.status = this.errorCodes.ERROR;
              } else {
                this.openaireSearchUtils.status = this.errorCodes.NOT_AVAILABLE;
              }

              this.disableForms = false;
          }
        );
      }
    }
  }

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

  keywordChanged(keyword) {
    this.openaireSearchUtils.keyword = keyword;
    this.buildQueryParameters();
    this.goTo(1);
  }

  funderChanged(funderId:string, funderName:string){
    this.selectedFunderId = funderId;
    this.selectedFunderName = funderName;

    this.buildQueryParameters();
    this.goTo(1);
  }

  buildQueryParameters() {
    this.queryParameters = "";

    if(this.openaireSearchUtils.keyword) {
      this.queryParameters = "q="+StringUtils.URIEncode(this.openaireSearchUtils.keyword);
    }

    if(this.selectedFunderId != "0") {
      this.queryParameters += this.queryParameters ? "&" : "";
      this.queryParameters += "fq=funder exact " + '"'+StringUtils.URIEncode(this.selectedFunderId)+ '"';
    }
  }

  goTo(page:number = 1){
    this.openaireSearchUtils.page=page;
    this.openaireSearchUtils.status = this.errorCodes.LOADING;
    this._getOpenaireProjects(this.queryParameters, page, 10);
  }
}
