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

import { OdooService } from "./odoo-service";
import { PouchService } from "./pouch-service";

import { getMetadataStorage } from "../odoo/utils/metadata-storage";

import "rxjs/add/observable/from";
import "rxjs/add/operator/concatMap";
import "rxjs/add/operator/map";

@Injectable()
export class DownloadService {

    constructor(
        public odoo: OdooService,
        public pouch: PouchService
    ) { 
    }

    /**
     *
     */
    do(): Observable<any> {
        return this.pouch.getAll("user")
            .concatMap(users => this.login(users.docs.shift()))
            .concatMap(logged => Observable.from(getMetadataStorage().getModels()))
            .concatMap(item => this.odoo.searchRead(item.model.name, []).map(r => {
                return Object.assign(r, { type: item.model.document });
            })).concatMap(data => this.store(data));
    }

    /**
     *
     */
    protected login(user: any): Observable<any> {
        this.odoo.initialize("http://localhost:8100");
        
        return this.odoo.login(user.db, user.username, user.password);
    }

    /**
     *
     */
    protected store(data: any): Observable<any> {
        let type = data.type;
        let records = data.records;
        
        return Observable.from(records).map((r: any) => {
            r.remote_id = r.id;
            delete r.id;
            
            return r;
        }).concatMap(item => this.pouch.save(Object.assign(item, { type: type, doc_state: "none" })));
    }
}