// import stringify = require('json-stringify-safe');
import { action, circular, excludedInJSON, immutable } from '../decorators';
import { config, history, utils, LEVEL_ENUM, Vertex, PackageJSON, App, Page, DataNode, View, Element, ExpressionNode, Logic, genFinalCode, ActionOptions, ACTION_MODE } from '..';
import { elementService, attributeService, lifecycleService, directiveService } from '../../service/page';

/**
 * 前端页面事件
 */
export class Lifecycle extends Vertex {
    /**
     * 概念类型
     */
    @immutable()
    public readonly level: LEVEL_ENUM = LEVEL_ENUM.lifecycle;
    /**
     * 页面事件 Id
     */
    @immutable()
    public readonly id: string = undefined;
    /**
     * 页面事件名
     */
    @immutable()
    public readonly name: string = undefined;
    /**
     * 页面事件逻辑 Id
     */
    @immutable()
    public readonly logicId?: string = undefined;
    /**
     * 所属页面 Id
     */
    @immutable()
    public readonly viewId: string = undefined;
    /**
     * 所属页面
     */
    @circular()
    @immutable()
    public readonly view: View = undefined;
    /**
     * @param source 需要合并的部分参数
     */
    constructor(source?: Partial<Lifecycle>) {
        super();
        source && this.assign(source);
    }
    /**
     * 添加页面事件
     */
    async create(none?: void, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        if (actionOptions?.actionMode !== ACTION_MODE.undoRedo) {
            const body = this.toJSON();
            utils.logger.debug('添加页面事件', body);
            const result: Lifecycle = await lifecycleService.create({
                headers: {
                    appId: config.defaultApp?.id,
                    operationAction: actionOptions?.actionName || 'Lifecycle.create',
                    operationDesc: actionOptions?.actionDesc,
                },
                body,
            });
            this.assign({ id: result.id });
        }

        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
        return this;
    }
    /**
     * 修改页面事件
     */
    async update(data?: Lifecycle, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        data && this.assign(data);
        if (actionOptions?.actionMode !== ACTION_MODE.undoRedo) {
            const body = this.toJSON();
            utils.logger.debug('修改页面事件', body);
            await lifecycleService.update({
                headers: {
                    appId: config.defaultApp?.id,
                    operationAction: actionOptions?.actionName || 'Lifecycle.update',
                    operationDesc: actionOptions?.actionDesc,
                },
                body,
            });
        }

        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
        return this;
    }
    /**
     * 保存
     * createOrUpdate 创建或更新
     */
    save() {
        return !this.id ? this.create() : this.update();
    }
    /**
     * 删除页面事件
    */
    @action('删除页面事件')
    async delete(none?: void, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        if (actionOptions?.actionMode !== ACTION_MODE.undoRedo) {
            if (this.id) {
                try {
                    await lifecycleService.delete({
                        headers: {
                            appId: config.defaultApp?.id,
                            operationAction: actionOptions?.actionName || 'Lifecycle.delete',
                            operationDesc: actionOptions?.actionDesc,
                        },
                        query: {
                            id: this.id,
                        },
                    });
                } catch(err) {
                    await config.defaultApp?.history.load();
                    throw err;
                }
            }
        }
        const index = this.view.$def.lifecycles.indexOf(this);
        ~index && this.view.$def.lifecycles.splice(index, 1);
        this.destroy();
        if (this.id) {
            if (this.view) {
                this.view.page.service.emit('pageTreeChange');
                this.view.emit('change');
            }
        }
        
        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
    }
    @action('选择页面事件名')
    selectName(name: string) {
        this.assign({ name });
        this.save();

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }
    }
    @action('选择页面事件逻辑')
    selectLogic(logicId: string) {
        this.assign({ logicId });
        this.save();

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }
    }
    /**
     * 从后端 JSON 生成规范的 Lifecycle 对象
     */
    public static from(source: any, view: View) {
        const lifecyle = new Lifecycle(source);
        lifecyle.assign({ view });
        return lifecyle;
    }
}

export default Lifecycle;
