/**
 * Created by stefania on 7/14/17.
 */
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { Page } from "../../domain/page";
import { HelpContentService } from "../../services/help-content.service";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';


@Component({
    selector: 'page-content-form',
    templateUrl: './page-help-content-form.component.html',
})

export class PageContentFormComponent implements OnInit{

    @Input('group')
    myForm: FormGroup;
    @Input('communityPid')
    communityPid: string;
    @Input('pageId')
    pageId: string;

    private availablePages : Page[] = [];
    private errorMessage: string;

    private ckeditorContent : string;
    public properties:EnvProperties = null;

    constructor(private route: ActivatedRoute,private _fb: FormBuilder, private _helpContentService: HelpContentService){}

    ngOnInit() {
        this.myForm = this.form;
        this.route.data
          .subscribe((data: { envSpecific: EnvProperties }) => {
             this.properties = data.envSpecific;
             this._helpContentService.getCommunityPages(this.communityPid, this.properties.adminToolsAPIURL).subscribe(
               pages => this.availablePages = pages,
               error => this.handleError('System error retrieving pages', error));
        });
    }

    public get form() {
        return this._fb.group({
            page : [this.pageId,Validators.required],
            community : this.communityPid,
            placement : ['', Validators.required],
            content : ['', Validators.required],
            order : ['1', Validators.required],
            isActive : true,
            isPriorTo : false,
            _id : '',
        });
    }

    public reset() {
        this.myForm.patchValue({
            page : '',
            community : this.communityPid,
            placement : '',
            content : [''],
            order : '1',
            isActive : true,
            isPriorTo : false,
            _id : ''
        });
        this.myForm.markAsPristine();
    }

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