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

@Injectable()
export class ProductAttributeLineSyncProvider {

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

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

            this.getUpdatedLines().then(lines => { 
                return lines;
            }).then(lines => {
                return this.odooProvider.put('product_attribute_line', lines);
            }).then(response => {
                console.log('product_attribute_line: product attribute lines modified sended');
                return this.odooProvider.get('product_attribute_line');
            }).then(lines => {
                return this.storeLines(lines);
            }).then(() => {
                console.log('product_attribute_line: product attribute lines downloaded');
                resolve();
            }).catch(e => { 
                reject(e);    
            });
        });

    }

     /**
     *
     */
    private getUpdatedLines(): Promise<any> {
        return new Promise((resolve, reject) => {
            this.dataProvider.getAll(DataProvider.DOCS.PRODUCT_ATTRIBUTE_LINE).then(lines => {
                lines = lines.filter(item => {
                    return item.doc_state === "updated" && item.remote_id;
                });
                
                resolve(lines.map(item => {
                    delete item.id;
                    return item;
                }));
            }).catch(e => {
                reject(e);
            });
        });
    }


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

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