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

@Injectable()
export class ProductAttributeValueSyncProvider {

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

    /**
     *
     */
    doSync(): Promise<any> {
        return new Promise((reject, resolve) => {
            this.odooProvider.get('product_attribute_value').then(values => {
                return values;
            }).then(lines => {
                return this.storeValues(lines);
            }).then(() => {
                console.log('product_attribute_value: product attribute values downloaded');
                resolve();
            }).catch(e => { 
                reject(e);    
            });
        });

    }

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

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