import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";

import { OdooRPCService } from "angular2-odoo-jsonrpc";
import { PouchService } from "./pouch-service";
import { SyncService } from "./sync-service";

import "rxjs/add/observable/fromPromise";
import "rxjs/add/observable/empty";
import "rxjs/add/operator/concat"

@Injectable()
export class AuthService {

    constructor(
        public odooRPC: OdooRPCService,
        public pouch: PouchService,
        public sync: SyncService
    ) { }

    /**
     *
     */
    private initialize(url: string, port?: number) {
        let host = url;

        if (port) {
            host = host + ":" + port;
        }
        
        this.odooRPC.init({
            odoo_server: host,
            http_auth: "username:password"
        });
    }

    /**
     *
     */
    signin(loginInformation: any): Observable<any> {
        this.initialize(loginInformation.host);

        return Observable.fromPromise(this.odooRPC.login(loginInformation.database, loginInformation.username, loginInformation.password))
            .concat(this.store(loginInformation));
    }

    /**
     *
     */
    skipSignin(): boolean {
        return !!localStorage.getItem("odoo");
    }

    /**
     *
     */
    signout(): Observable<any> {
        return Observable.fromPromise(this.odooRPC.logout());
    }

    /**
     *
     */
    private store(loginInformation: any): Observable<any> {
        localStorage.setItem("odoo", JSON.stringify(loginInformation));
        
        return Observable.empty();
    }
}