application.service.ts 8.34 KB
import {Injectable} from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Router }   from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


import { AppSettings, User, UserProfile } from '../model/data-model';
import { State } from '../model/db-tables';
import { AccountType } from '../model/db-tables';
import { Country } from '../model/db-tables';
import { SecurityQuestions } from '../model/db-tables';
import { LicenseType } from '../model/db-tables';

@Injectable()
export class ApplicationService {
    appSettingsLoaded: boolean;
    appSettings: AppSettings;
    currentUser: User;
    loggedIn: boolean;

    userId: number;
    firstName: string;
    lastName: string;
    emailId: string;
    userInfo: UserProfile;

    apiUrl: "http://localhost:85/AIAHTML5.Server/api/";

    constructor(private http: Http, private router: Router) {
        if (this.currentUser == null) {
            var user = localStorage.getItem("currentUser");

            if (user != null) {
                this.currentUser = JSON.parse(user);
                this.loggedIn = true;
            }
        }

        this.userId = 0;
        this.firstName = "";
        this.lastName = "";
        this.emailId = "";
            
    }

    public getAppSettings(applicationName: string): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let params = new URLSearchParams();
        params.set("applicationName", applicationName);
        params.set("userId", this.currentUser._id);

        return this.http.get('DentalDecks.Server/api/AppSettings', { headers: headers, search: params })
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getMenuItemsWithNoChildren(menuItems: any): any {
        if (this.appSettingsLoaded) {
            let menuItemsSubset: Array<any> = new Array<any>();
            for (var i = 0; i < menuItems.length; i++) {
                if (menuItems[i].menuItems == null) {
                    for (var j = 0; j < menuItems[i].roles.length; j++) {
                        if (menuItems[i].roles[j] == this.currentUser.role) {
                            menuItemsSubset.push(menuItems[i]);
                            break;
                        }
                    }  
                }
            }
            return menuItemsSubset;
        }
    }

    public getMenuItemsWithChildren(menuItems: any): any {
        if (this.appSettingsLoaded) {
            let menuItemsSubset: Array<any> = new Array<any>();
            for (var i = 0; i < menuItems.length; i++) {
                if (menuItems[i].menuItems != null) {
                    for (var j = 0; j < menuItems[i].roles.length; j++) {
                        if (menuItems[i].roles[j] == this.currentUser.role) {
                            menuItemsSubset.push(menuItems[i]);
                            break;
                        }
                    }
                }
            }
            return menuItemsSubset;
        }
    }

    public login(applicationName: string, username: string, password: string): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let params = new URLSearchParams();
        params.set("applicationName", applicationName);
        params.set("username", username);
        params.set("password", password);

        return this.http.get('DentalDecks.Server/api/Authenticate', { headers: headers, search: params })
            .map(this.extractData)
            .catch(this.handleError);
    }

    public logout(): void {
        this.currentUser = null;
        localStorage.removeItem("currentUser");
        this.router.navigate(['/login']);
    }

    public resetPassword(username: string): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let user: any = new Object();
        user.emailAddress = username;

        return this.http.post('DentalDecks.Server/api/Password', JSON.stringify(user), { headers: headers })
            .map(this.extractData)
            .catch(this.handleError);
    }

    public updatePassword(userId: string, password: string): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let user: any = new Object();
        user.userId = userId;
        user.password = password;

        return this.http.post('DentalDecks.Server/api/UpdatePassword', JSON.stringify(user), { headers: headers })
            .map(this.extractData)
            .catch(this.handleError);
    }

    public isResetPasswordExpired(userId: string): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let params = new URLSearchParams();
        params.set("userId", userId);

        return this.http.get('DentalDecks.Server/api/Password', { headers: headers, search: params })
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getLongDate(date: any): string {
        let returnValue: Date = new Date(date);
        return returnValue.toLocaleDateString();
    }

    getDateTime(date: any): string {
        let orderDate: string = "";
        if (date != null && date != "")
            orderDate = new Date(date).toLocaleDateString() + " " + new Date(date).toLocaleTimeString();

        return orderDate;
    }

    getRelativeDate(date: any): string {
        if (date != null) {
            date = new Date(date);

            var delta = Math.round((+new Date - date) / 1000);

            var minute = 60,
                hour = minute * 60,
                day = hour * 24,
                week = day * 7;

            var fuzzy: string;

            if (delta < 30) {
                fuzzy = 'just now.';
            } else if (delta < minute) {
                fuzzy = delta + ' seconds ago.';
            } else if (delta < 2 * minute) {
                fuzzy = 'a minute ago.'
            } else if (delta < hour) {
                fuzzy = Math.floor(delta / minute) + ' minutes ago.';
            } else if (Math.floor(delta / hour) == 1) {
                fuzzy = '1 hour ago.'
            } else if (delta < day) {
                fuzzy = Math.floor(delta / hour) + ' hours ago.';
            } else if (delta < day * 2 && delta > day) {
                fuzzy = 'yesterday';
            } else {
                fuzzy = Math.floor(delta / (60 * 60 * 24)) + ' days ago';
            }

            return fuzzy;
        } else {
            return "";
        }
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }
    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

    public getAccountTypes(): Observable<any> {
        return this.http.get('http://localhost:85/AIAHTML5.Server/api/accounttype')
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getStates(): Observable<any> {
        return this.http.get('http://localhost:85/AIAHTML5.Server/api/state')
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getCountries(): Observable<any> {
        return this.http.get('http://localhost:85/AIAHTML5.Server/api/country')
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getSecurityQuestions(): Observable<any> {
        return this.http.get('http://localhost:85/AIAHTML5.Server/api/securityquestionlist')
            .map(this.extractData)
            .catch(this.handleError);
    }

    public getLicenseTypes(): Observable<any> {
        return this.http.get('http://localhost:85/AIAHTML5.Server/api/licensetype')
            .map(this.extractData)
            .catch(this.handleError);
    }
}