import {
  AfterViewInit,
  Component,
  Input,
  OnInit
} from '@angular/core';
import { Configuration } from 'src/app/models/Page';
import {ActivatedRoute, Router} from "@angular/router";
import  {AppService} from "src/app/services/app.service";
import {User} from 'src/app/models/User';
import {Community} from 'src/app/models/Community';
import { UtilsService } from 'src/app/services/utils.service';

 
@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.css']
})
export class PageComponent implements OnInit, AfterViewInit {
	
  @Input() configuration?: Configuration;
  
  @Input() selectedCommunity: Community = this.app.community;
  
  user: User = this.app.user;
  
  communities : Community[] = [];
  
  event : any;
  
  constructor(private route: ActivatedRoute, 
		  private router: Router, 
		  public app: AppService,
		  private utils: UtilsService
		  ) { }
  loaded = false;
  
  ngOnInit(): void {
	  
	  if(this.communities.length === 0){
	  
	  for(var i = 0; i < this.user.usercommunities.length ; i++){
		  this.communities.push(this.user.usercommunities[i]);
		}
	  if (this.user.usercommunities.length === 1){
		  this.app.community = this.user.usercommunities[0];
		  this.selectedCommunity = this.user.usercommunities[0];
	  } 
	  }
	   if(this.app.community) 
		  	  this.registerParams("communityid", this.selectedCommunity.communityid);

    this.loaded = false;
  }
  
  ngAfterViewInit(): void {
    setTimeout(() => { this.loaded = true; }, 500);
   }
  
  setCommunity(event: Event){
	  
	 this.registerParams("communityid", this.selectedCommunity.communityid);
	 this.app.community = this.selectedCommunity;
	}
  
  registerParams(paramName: string, value?: string){
	  let queryParams: any = {};
	  queryParams[paramName] = value;

	  if (this.configuration)
		  this.configuration.selectedCommunity = this.selectedCommunity.communityid;
	  
	  this.router.navigate(['.'], {
	      relativeTo: this.route,
	      queryParams: queryParams,
	      queryParamsHandling: 'merge',
	      skipLocationChange: false
	    });
/**
 * Il comando seguente impedisce la modifica delle pagine attraverso i vari menu. 
 */
//	  this.router.routeReuseStrategy.shouldReuseRoute = function () {
//	        return false;
//	    }
  }
}
