﻿import { Injectable, Component } from '@angular/core';
import { Input, Output, EventEmitter } from '@angular/core';

import { AbstractControl } from '@angular/forms';

import { IEntityDataService, ILoginService, IEmptyConstruct, IDataStructure } from "../interfaces/index";
import { ChangesCommit, DataChanged } from "../interfaces/index";
import { NotificationService } from "../services/index";

@Component({
    selector: 'user-profile',
    templateUrl: './profile-page.component.html'
})
@Injectable()
export abstract class IProfilePageComponent {

    /** Entity data source Type */
    @Input() entityEditing: IDataStructure;

    /** The saved event emit property */
    @Output() entitySaved: EventEmitter<IDataStructure> = new EventEmitter<IDataStructure>();

    /** The submitted event emit property */
    @Output() formSubmitted: EventEmitter<ChangesCommit> = new EventEmitter<ChangesCommit>();

    /** The busy flag to show or hide busy-overlay.component */
    @Output() busy: boolean = false;

    /** The inprogress change ID */
    protected inProgressChangeID: string = null;

    /** The error description */
    protected errorDescription: any = {};

    /**
     * Represents a IProfile page component.
     * @param entityService IEntityDataService
     * @param loginService ILoginService
     */
    constructor(protected entityService: IEntityDataService, protected loginService: ILoginService, protected notifications: NotificationService) {

        var that = this;
        this.entityService.dataObserver.subscribe((dataChanged: DataChanged) => {
            if (that.inProgressChangeID && that.inProgressChangeID == dataChanged.ID) {
                that.inProgressChangeID = null;
                that.busy = false;
                if (that.entitySaved) {
                    dataChanged.data.map((data: IDataStructure) => {
                        that.entitySaved.next(data);
                    });
                    //that.entitySaved.next(dataChanged.data);
                }
            }
        });
        this.entityService.registerNewChangesStream(this.formSubmitted);
    }

    /**
     * Email validator
     */
    emailValidator() {
        return function (ac: AbstractControl) {
            if (ac.value) {
                var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                if (!emailReg.test(ac.value)) return { invalidEmail: true };
            }
        }
    }

    /**
     * Save data
     * @param entity IDataStructure
     */
    abstract save(DataStructure: IEmptyConstruct, entity: IDataStructure): void;
}