import { Injectable } from '@angular/core';
import { OdooProvider } from './odoo-provider';
import { DataProvider } from './data-provider';
import { PreferencesProvider } from './preferences-provider';

@Injectable()
export class ToolsProvider {

    constructor(
        public odooProvider: OdooProvider,
        public dataProvider: DataProvider,
        public preferencesProvider: PreferencesProvider
    ) { }
    
    /**
     *
     */
    initializeDatabase(): Promise<any> {
        return new Promise((resolve, reject) => { 
            Promise.all([
                this.getUserInformation()
            ]).then(() => { 
                resolve();
            }).catch(e => { 
                reject(e);
            });
        });
    }

    /**
     *
     */
    private getUserInformation(): Promise<any> {
        return new Promise((resolve, reject) => {

            this.dataProvider.getAll("user").then(users => {

                if (users.length == 0) {
                    this.odooProvider.get("user").then(users => {
                
                    let user = users.filter(item => {
                        return item.jwt_token === this.preferencesProvider.getToken();
                    });

                    this.dataProvider.save("user", user[0]).then(user => {
                        this.preferencesProvider.setCompany(user.company_id);
                        this.preferencesProvider.setPartner(user.partner_id);
                        
                        resolve();
                    }).catch(e => { 
                        reject(e);
                    });
                        
                }).catch(e => { 
                    console.log(e);
                    reject(e);
                });
                   
                } else {
                    resolve(); 
                }
            });
        });
    }

    /**
     *
     */
    clearPreferences(): void {
        this.preferencesProvider.clearPreferences();
    }

    /**
     *
     */
    getCompany(): Promise<any> {
        return new Promise((reject, resolve) => { 
            this.dataProvider.getAll("user").then(data => {
                resolve(data.users[0].company_id);
            }).catch(e => {
                reject(e);
            });
        });
       
    }
}