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

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

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

import "rxjs/add/operator/filter";
import "rxjs/add/observable/from";
import "rxjs/add/operator/concatMap";
import "rxjs/add/operator/map";
import "rxjs/add/operator/groupBy";
import "rxjs/add/operator/mergeAll";

@Injectable()
export class UploadService {

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

    do(): Observable<any> {
        return this.pouch.getAll("user")
            .concatMap(users => this.login(users.docs.shift()))
            .concatMap(logged => Observable.from(getMetadataStorage().getModels()))
            .concatMap(item => this.pouch.getAll(item.model.document))
            .concatMap(result => Observable.from(result.docs).filter((r: any) => {
                return r.doc_state == "none";
            }).groupBy((r: any) => {
                return r.doc_state;
            })).mergeAll().concatMap(doc => this.processDocument(doc));    
    }
    
    /**
     *
     */
    private login(user: any): Observable<any> {
        this.odoo.initialize("http://localhost:8100");
        
        return this.odoo.login(user.db, user.username, user.password);
    }

    /**
     *
     */
    protected processDocument(doc: any): Observable<any> {
        let id: number = doc.remote_id;
        let model: string = doc.type;

        delete doc.type;
        delete doc.remote_id;

        if (doc.doc_state === "created") {
            this.odoo.create(model, doc);
        } else if (doc.doc_state === "updated") {
            return this.odoo.write(model, [[id], doc]);
        } 

        return this.odoo.unlink(model, [[id]]);
    }
}