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

@Injectable()
export class ProductAttributeSyncProvider {

    constructor(
        public dataProvider: DataProvider,
        public odooProvider: OdooProvider
    ) { }

    /**
     *
     */
    doSync(): Promise<any> {
        return new Promise((reject, resolve) => {
            this.odooProvider.get('product_attribute').then(attrs => {
                return attrs;
            }).then(attrs => {
                return this.storeAttributes(attrs);
            }).then(() => {
                console.log('product_attribute: product attributes downloaded');
                resolve();
            }).catch(e => { 
                reject(e);    
            });
        });

    }

        /**
     *
     */
    private storeAttributes(attrs: Array<any>): Promise<any> {
        return new Promise((reject, resolve) => {
            this.dataProvider.deleteAll(DataProvider.DOCS.PRODUCT_ATTRIBUTE).then(() => {
                return;
            }).then(() => {
                return this.dataProvider.save(DataProvider.DOCS.PRODUCT_ATTRIBUTE, attrs.map(item => {
                    item.remote_id = item.id;
                    item.doc_state = "sync";
                    delete item.id;

                    return item;
                }));
            }).then(() => {
                resolve();
            }).catch(e => { 
                reject(e);    
            });
        });
    }
}