import {Component, OnInit, Input}                        from '@angular/core';
import {FormGroup, FormArray, FormBuilder, Validators}   from "@angular/forms";
import {ActivatedRoute, Router}                          from '@angular/router';

import {HelpContentService}                              from "../../../services/help-content.service";
import {CommunityService}                                from "../../../openaireLibrary/connect/community/community.service";
import {EnvProperties}                                   from '../../../openaireLibrary/utils/properties/env-properties';

@Component({
    selector: 'community-edit-form',
    templateUrl: './community-edit-form.component.html',
})

export class CommunityEditFormComponent implements OnInit{

    @Input('group')
    myForm: FormGroup;

    public errorMessage: string;

    public res=[];

    params: any;

    public communityId = null;
    public community = null;
    public properties:EnvProperties = null;

    constructor (private route: ActivatedRoute,
                 private _router: Router,
                 public _fb: FormBuilder,
                 private _helpContentService: HelpContentService,
                 private _communityService: CommunityService){ }


    ngOnInit() {
        this.route.data .subscribe((data: { envSpecific: EnvProperties }) => {
            this.properties = data.envSpecific;
            this.route.queryParams.subscribe(
              communityId => {
                    this.communityId = communityId['communityId'];
                    if (this.communityId != null) {
                        this._communityService.getCommunity(this.properties.communityAPI+this.communityId).subscribe (
                          community => {
                                this.community = community;
                                this.params = {community: encodeURIComponent('"'+community.queryId+'"')};
                                console.log(community);
                          });
                    }
             });
        });
    }

    public get form() {
        return this._fb.group({
            _id : '',
            name : ['', Validators.required]
        });
    }

    public reset() {
        this.myForm.patchValue({
            name : '',
            _id : ''
        });
    }

    handleError(message: string, error) {
        if(error == null) {
            this.reset();
        }
        this.errorMessage = message + ' (Server responded: ' + error + ')';
    }
}
