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

import * as PouchFind from "pouchdb-find";

import "rxjs/add/observable/throw";
import "rxjs/add/observable/fromPromise";

PouchDB.plugin(PouchFind);

@Injectable()
export class PouchService {

    pouchDB: any;

    constructor() {
        this.initialize();
    }

    /**
     *
     */
    private initialize(): void {
        this.pouchDB = new PouchDB("odoo", {
            auto_compaction: true
        });
        this.pouchDB.createIndex({
            index: {
                fields: ['type']
            }
        }).then(response => console.log(response)).catch(error => console.log(error));
    }

    /**
     *
     */
    save(data: any): Observable<any> {
        if (!data.type) {
            return Observable.throw("Error: Cannot save data without type");
        }

        return Observable.fromPromise(this.pouchDB.post(data));
    }

    /**
     *
     */
    remove(data: any): Observable<any> {
        if (!data._id || !data._rev) {
            return Observable.throw("Error: Cannot remove data without id or rev");
        }

        return Observable.fromPromise(this.pouchDB.remove(data));
    }

    /**
     *
     */
    get(data: any): Observable<any> {
        if (!data._id) {
            return Observable.throw("Error: Cannot get data without id");
        }

        return Observable.fromPromise(this.pouchDB.get(data._id));
    }

    /**
     *
     */
    getAll(type: string): Observable<any> {
        return Observable.fromPromise(this.pouchDB.find({
            selector: {
                type: {
                    $eq: type
                }
            }
        }));
    }
}
