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 { DivId } from "../../domain/divId";
import { HelpContentService } from "../../services/help-content.service";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';


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

export class DivContentFormComponent implements OnInit{

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

    showPageSelect: boolean = true;

    private availablePages : Page[] = [];
    private availableDivs : DivId[] = [];

    private errorMessage: string;

    private ckeditorContent : string;

    constructor(private route: ActivatedRoute, private _fb: FormBuilder, private _helpContentService: HelpContentService){}
    public properties:EnvProperties = null;

    ngOnInit() {
      this.myForm = this.form;
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           if(this.pageId) {
             this.showPageSelect = false;
             this.getDivs(this.pageId);
           } else {
             this._helpContentService.getCommunityPagesWithDivId(this.communityPid, this.properties.adminToolsAPIURL).subscribe(
               pages => this.availablePages = pages,
               error => this.handleError('System error retrieving pages', error));
             }

        });

    }

    public pageSelected(event) {
      this.getDivs(event.target.value);
    }

    public getDivs(pageId: string) {
      console.info(pageId);
      this._helpContentService.getDivIdsFull(this.communityPid, pageId, this.properties.adminToolsAPIURL).subscribe(
          divs => {
            this.availableDivs = divs;
            this.pageId = pageId;
          },
          error => this.handleError('System error retrieving pages', error));
    }

    public selectedDiv(event) {
      console.info(event.target.value);
    }

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

    public reset() {
        this.myForm.patchValue({
          divId: '',
          content: '',
          isActive: true,
          _id : ''
        });
        this.myForm.markAsPristine();
    }

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