import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { IUser, IUserAccounts, IUserCredentials } from './user.model';

import { TokenService } from '../token/token.service';

import { IApiError, IApiResponseError, IApiResponseSuccess, isApiResponseError } from '../token/apiresponse.model';

import { ErrorObservable } from 'rxjs/observable/ErrorObservable';

@Injectable()
export class UserService {
    user: IUser;
    userAccounts: IUserAccounts;
    testParam: string;
    get UserCredentials(): IUserCredentials {
        return this.user || this.userCredentials;
    }
    set UserCredentials(value: IUserCredentials) {
        this.userCredentials = value;
    }
    private userCredentials: IUserCredentials;

    constructor(private http: Http, private tokenService: TokenService) { }
    createUser(user: IUser): Observable<IUser> {
        const headers: Headers = new Headers({
            'Content-Type': 'application/json',
            Authorization: this.tokenService.authorization
        });
        const options: RequestOptions = new RequestOptions({ headers });
        const req: Observable<Response> = this.http.post(`${SETTINGS.API_URL}/general/newuser/${this.testParam}`, user, options);
        return req.map((response: Response) => {
            const data: IApiResponseError | IApiResponseSuccess<number> = response.json();
            if (isApiResponseError(data)) {
                throw Observable.throw(data.error);
            }
            user.userId = data.result;
            this.user = user;
            return user;
        }).catch(this.handleError);
    }
    loadUser(): Observable<IUserAccounts> {
        const headers: Headers = new Headers({
            'Content-Type': 'application/json',
            Authorization: this.tokenService.authorization
        });
        const options: RequestOptions = new RequestOptions({ headers });
        const req: Observable<Response> = this.http.get(`${SETTINGS.API_URL}/account/useraccounts`, options);
        return req.map((response: Response) => {
            const data: IApiResponseError | IApiResponseSuccess<IUserAccounts> = response.json();
            if (isApiResponseError(data)) {
                throw data.error;
                // return Observable.throw(data.error.msg);
            }
            this.userAccounts = data.result;
            return data.result;
        });
    }
    updateUser(user: IUser): Observable<IUser> {
        const headers: Headers = new Headers({
            'Content-Type': 'application/json',
            Authorization: this.tokenService.authorization
        });
        const options: RequestOptions = new RequestOptions({ headers });
        const req: Observable<Response> = this.http.put(`${SETTINGS.API_URL}/general/user`, user, options);
        return req.map((response: Response) => {
            const data: IApiResponseError | IApiResponseSuccess<IUser> = response.json();
            if (isApiResponseError(data)) {
                throw Observable.throw(data.error);
            }
            return data.result;
        });
    }
    private handleError(error: IApiError): Observable<IUser> {
        console.log(error);
        return Observable.throw(error.msg || error);
    }
}
