import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Router } 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';

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';

@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;
    @Input('page')
    page: Page;
    placements = {"top": false, "bottom": false, "left": false, "right": false}

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

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

    public showLoading: boolean = true;
    public errorMessage: string = '';
    @Input() updateErrorMessage: string = '';

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

    ngOnInit() {
        this.myForm = this.form;
        this.route.data
          .subscribe((data: { envSpecific: EnvProperties }) => {
             this.properties = data.envSpecific;

             if(!Session.isLoggedIn()){
               this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
             } else {
                 if(!this.pageId) {
                     this.myForm.valueChanges.subscribe(value => {
                         let pageId = value.page;
                         this._helpContentService.getPage(pageId, this.properties.adminToolsAPIURL).subscribe(page => {
                            this.setPlacements(page);
                         });
                     });
                 }
                 this._helpContentService.getPages(this.properties.adminToolsAPIURL, this.communityPid, true).subscribe(
                   pages => {
                       this.availablePages = pages;
                       this.showLoading = false;
                   },
                   error => this.handleError('System error retrieving pages', error));
             }
        });
    }

    public setPlacements(page: Page) {
      this.placements.top = page.top;
      this.placements.bottom = page.bottom;
      this.placements.left = page.left;
      this.placements.right = page.right;
    }

    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;
        console.log('Server responded: ' + error);

        this.showLoading = false;
    }
}
