﻿import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { TfabricaUserData } from '../models/tfabrica.userdata.model';
import { TfabricaSettingsData } from '../models/tfabrica.settings.model';

import { TfabricaSharedService } from '../main/tfabrica.shared.service';

@Injectable()
export class TfabricaLoginService {

    constructor(
        private _http: Http,
        private _shared: TfabricaSharedService
    ) { }

    loginUrl = "/api/Auth/Authenticate";

    public login(username: string, password: string): Observable<TfabricaUserData> {

        this.loginUrl = this._shared.appSettings.authenticationApiUrl;
        this.loginUrl = this._shared.appSettings.getauthenticationApiUrl();

        console.log("Start call service: " + this.loginUrl);

        let bodyString = { Username: username, Password: password };
        let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
        let options = new RequestOptions({ headers: headers }); // Create a request option

        return this._http.post(this.loginUrl, bodyString, options) // ...using post request
            .map((res) => this.extractLoginData(res)) // ...and calling .json() on the response to return data
            .catch((err) => this.handleError(err)); //...errors if any
    }

    private extractLoginData(res: Response) {
        if (res.status < 200 || res.status >= 300) {
            throw new Error('Bad response status: ' + res.status);
        }
        let userData = new TfabricaUserData();

        let response = res.json();
        userData.username = response['user']['username'];
        userData.name = response['user']['name'];
        userData.surname = response['user']['surname'];
        userData.sourceImage = response['user']['sourceImage'];
        userData.token = response.token;

        userData.isLogged = true;
        return userData || {};
    }

    private handleError(error: any) {
        let errMsg = error.message || 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }


    logout(): any {
        localStorage.removeItem('userData');
    }

    getUser(): any {
        return JSON.parse(localStorage.getItem('userData'));
    }

    isLoggedIn(): boolean {
        return this.getUser() !== null;
    }

    updateUser(userData: TfabricaUserData) {
        localStorage.setItem('userData', JSON.stringify(userData));
    }

}



export var AUTH_PROVIDERS: Array<any> = [
    { provide: TfabricaLoginService, useClass: TfabricaLoginService }
];
