import {Component, OnInit, ElementRef} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';


import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {LayoutService} from '../../../openaireLibrary/services/layout.service';
import {Session} from '../../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from "../../../openaireLibrary/utils/HelperFunctions.class";

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

export class CommunityLayoutComponent implements OnInit {

    public showLoading = true;
    public errorMessage  = '';

    public successfulSaveMessage = '';
    public successfulResetMessage = '';

    public hasChanged = false;
    public communityId = null;
    public layout = null;
    public properties: EnvProperties = null;

    constructor (private element: ElementRef,
                 private route: ActivatedRoute,
                 private _layoutService: LayoutService,
                 private _router: Router) { }


    ngOnInit() {
        this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
            this.properties = data.envSpecific;
            this.route.queryParams.subscribe(
              communityId => {
                HelperFunctions.scroll();
                this.communityId = communityId['communityId'];
                    if (this.communityId != null && this.communityId !== '') {
                      this.showLoading = true;
                      this.errorMessage = '';
                      this._layoutService.getLayout(this.communityId,
                            this.properties.adminToolsAPIURL).subscribe (
                            layout => {
                                this.layout = layout;
                                this.showLoading = false;
                            },
                            error => this.handleError('System error retrieving community layout', error)
                      );
                    }
             });
        });
    }

    public updateLayout() {
        if (!Session.isLoggedIn()) {
            this._router.navigate(['/user-info'], { queryParams:
                    { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
        } else if (this.communityId != null && this.communityId !== '') {
            this.showLoading = true;
            this._layoutService.saveLayout(this.communityId,
                this.properties.adminToolsAPIURL, this.layout).subscribe (
                layout => {
                    this.layout = layout;
                    this.showLoading = false;
                    this.handleSuccessfulSave('Community Layout saved!');
                },
                error => this.handleError('System error saving community layout', error)
            );
            this.resetChange();
        }
    }

    public resetLayout() {
        if (!Session.isLoggedIn()) {
            this._router.navigate(['/user-info'], { queryParams:
                    { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
        } else if (this.communityId != null && this.communityId !== '') {
            this.showLoading = true;
            this._layoutService.getLayout(this.communityId,
                this.properties.adminToolsAPIURL).subscribe (
                layout => {
                    this.layout = layout;
                    this.showLoading = false;
                    this.handleSuccessfulReset('Community Layout reset!');
                },
                error => this.handleError('System error retrieving community layout', error)
            );
            this.resetChange();
        }
    }

    public loadDefaultLayout() {
        if (!Session.isLoggedIn()) {
            this._router.navigate(['/user-info'], { queryParams:
                    { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
        } else if (this.communityId != null && this.communityId !== '') {
            this.showLoading = true;
            this._layoutService.loadDefaultLayout(this.communityId,
                this.properties.adminToolsAPIURL).subscribe (
                layout => {
                    this.layout = layout;
                    this.showLoading = false;
                    this.handleSuccessfulReset('Default Community Layout has been loaded!');
                },
                error => this.handleError('System error loading default community layout', error)
            );
            this.resetChange();
        }
    }

    private change() {
        this.hasChanged = true;
        this.successfulSaveMessage = '';
        this.successfulResetMessage = '';
    }

    private resetChange() {
        this.hasChanged = false;
    }

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

        this.showLoading = false;
    }

    handleSuccessfulSave(message) {
        this.showLoading = false;
        this.successfulSaveMessage = message;
    }

    handleSuccessfulReset(message) {
        this.showLoading = false;
        this.successfulResetMessage = message;
    }
}
