import { Injectable } from '@angular/core';
import PouchDB from 'pouchdb';
import * as Relational from 'relational-pouch';

PouchDB.plugin(Relational);

@Injectable()
export class DataProvider {

    data: any;

    constructor() {
        this.initialize();
    }

    /**
     *
     */
    private initialize(): void {
        this.data = new PouchDB('odoo');

        this.data.setSchema([
            {
                singular: 'partner',
                plural: 'partners'
            },
            {
                singular: 'user',
                plural: 'users',
                relations: {
                    partner: {
                        belongsTo: 'partner'
                    }
                }
            },
            {
                singular: 'currency',
                plural: 'currencies'
            },
            {
                singular: 'company',
                plural: 'companies',
                relations: {
                    currency: {
                        belongsTo: 'currency'
                    }
                }
            },
            {
                singular: 'product',
                plural: 'products',
                relations: {
                    company: {
                        belongsTo: 'product'
                    }
                }
            },
            {
                singular: 'warehouse',
                plural: 'warehouses',
            },
            {
                singular: 'stock',
                plural: 'stocks'
            },
            {
                singular: 'lead',
                plural: 'leads',
                relations: {
                    partner: {
                        belongsTo: 'partner'
                    }
                }
            }
        ]);
    }

    /**
     *
     */
    save(type: string, data: any): any {
        return new Promise((resolve, reject) => {
            resolve(this.data.rel.save(type, data));
        });
    }

    /**
     *
     */
    delete(type: string, data: any): any {
        return new Promise((resolve, reject) => {
            resolve(this.data.rel.del(type, data));
        });
    }

    /**
     *
     */
    getAll(type: string): any {
        return new Promise((resolve, reject) => {
            resolve(this.data.rel.find(type));
        });
        
    }
}
