import { Component, ViewChild, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
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 {SearchDataprovidersService} from '../../../openaireLibrary/services/searchDataproviders.service';
import {RouterHelper} from '../../../openaireLibrary/utils/routerHelper.class';
import {DOI, StringUtils} from '../../../openaireLibrary/utils/string-utils.class';
import {ManageCommunityContentProvidersService} from '../../../services/manageContentProviders.service';
import {Session} from '../../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';

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

export class AddContentProvidersComponent implements OnInit {
  @Input() communityContentProviders = [];

  private community: string = '';

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

  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 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._getOpenaireContentProviders("", 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 _searchContentProvidersService: SearchDataprovidersService, private _manageCommunityContentProvidersService: ManageCommunityContentProvidersService) {
    this.errorCodes = new ErrorCodes();
    this.openaireSearchUtils.status = this.errorCodes.LOADING;
  }

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

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

  public removeContentProvider(contentProviderId: string, communityContentProviderId: string) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.subRemove = this._manageCommunityContentProvidersService.removeContentProvider(this.properties, this.community, contentProviderId).subscribe(
        data => {
          //console.info(data);
        },
        err => {
          console.log(err);
        },
        () => {
          this.undo[communityContentProviderId] = "";
        }
      )
    }
  }

  public inCommunity(contentProvider: any): any {
    for(let communityContentProvider of this.communityContentProviders) {
      if(communityContentProvider.openaireId == contentProvider.id) {
        return true;
      }
    }

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

  private _getOpenaireContentProviders(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.openaireContentProviders = [];
        this.openaireSearchUtils.totalResults = 0;

        this.subResults = this._searchContentProvidersService.searchDataproviders(parameters, null, page, size, [], this.properties).subscribe(
          data => {
              this.undo = {};
              this.openaireSearchUtils.totalResults = data[0];
              this.openaireContentProviders = data[1];

              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);
  }

  buildQueryParameters() {
    this.queryParameters = "";

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

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