import { BaseView } from "./base-view";
import { PouchService } from "../services/pouch-service";
import { Observable } from "rxjs/Observable";

import { EventsManager } from "../base/events/event-manager";

export abstract class BaseDetailsView<T> extends BaseView<T> {

    item: T;
    kind: string;
    action: string;

    constructor(c: { new (): T; }, item?: T, kind?: string) {
        super(c, PouchService);

        this.item = item;
        this.kind = kind;
        this.action = this.itemExists() ? "to_update" : "to_create";
    }

    /**
     * 
     */
    getItem(): T {
        return this.item;
    }

    /**
     * 
     * @param item 
     */
    setItem(item: T) {
        this.item = item;
    }

    /**
     * 
     */
    getKind(): string {
        return this.kind;
    }

    /**
     * 
     * @param kind 
     */
    setKind(kind: string): void {
        this.kind = kind;
    }

    /**
     * 
     */
    getAction(): string {
        return this.action;
    }

    /**
     * 
     * @param action 
     */
    setAction(action: string): void {
        this.action = action;
    }

    /**
     * 
     */
    itemExists(): boolean {
        try {
            return !!Object.keys(this.getItem()).length;   
        } catch (error) {
            return false;
        }
    }

    /**
     * 
     */
    cleanItem(): void {
        this.setItem(Object.create(null));
    }

    /**
     * 
     * @param data 
     */
    performSave(): void {
        this.setItem(Object.assign(this.getItem(), { odoo_model: super.getModelName(), odoo_status: this.getAction() }));
        super.getInjectable(PouchService).save(this.getItem()).subscribe(result => {
            EventsManager.publish("app:changed", {
                action: this.getAction() === "to_create" ? "add" : "update",
                item: Object.assign(this.getItem(), { _id: result.id, _rev: result.rev })
            });
        }, error => {
            EventsManager.publish("app:error", error);
        });
    }
}