/**
 * Created by jd on 19/02/2016.
 */
import { Injectable } from "@angular/core";
import { WebApiService } from "./WebApiService";

import { Response } from "@angular/http";

import { IToken } from "../models/IToken";
import { Observer } from "rxjs/Observer";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { IUsuario } from "./OdisseiaDataBase/IUsuario";

@Injectable()
export class AuthService
{
    private _token:IToken;
    private _clientId:string = "BIAClient";
    private _clientSecret:string = "0c7f1fd8-bfcd-472e-89ee-1d4f8d362f37";
    private _currentUser:IUsuario;

    public WhenUserChanged = new Subject<IUsuario>();


    public setClientCredentials = ( clientId:string, clientSecret:string ):void =>
    {
        this._clientId = clientId;
        this._clientSecret = clientSecret;
    };

    constructor( private webApiService:WebApiService)
    {

    }


    public loginUser = ( newuser:IUsuario ):void =>
    {
        if (newuser != null)
        {
            this._currentUser = newuser;
            this.WhenUserChanged.next(newuser);
        }
    };


    public lougoutUser = ():void =>
    {
        this._currentUser = null;
        this.WhenUserChanged.next(null);
    };


    public IsUserAuthenticated = ():Observable<boolean> =>
    {
        var observable = Observable.create(( observer:Observer<boolean> ) =>
        {
            // this.dataBaseService.token.toArray()
            //     .then((tokens:IToken[]) =>
            //     {
            //         // if (tokens.length > 0)
            //         //     observer.next(true);
            //         // else
            //         observer.next(false);
            //         observer.complete();
            //     });


        });

        return observable;


    };

    public AuthUser = ( username:string, password:string ):Observable<IToken> =>
    {
        var data = "grant_type=password&client_id=" + this._clientId + "&client_secret=" + this._clientSecret + "&username=" + username + "&password=" + password;

        var result = this.webApiService
            .Resource("token")
            .CanSendToken(false)
            .Content(data)
            .ContentType("application/x-www-form-urlencoded")
            .Method("POST")
            .Execute<IToken>();

        result.subscribe(
            ( token:IToken )=>
            {
                localStorage.setItem("token", JSON.stringify(token));
                this._token = token;

            });

        return result;
    };

}