import poster from "./poster";
import Vue from 'vue'
import {uniqueId} from 'lodash'

const state = {
    snapshots: [],
    snapshots2: [],
    index: -1,
    maxIndex: 100
}

const getters = {
    canUndo() {
        return state.index > 0;
    },
    canRedo() {
        return state.index < state.snapshots.length - 1;
    }
}

const actions = {}

const mutations = {

    clear(state) {
        state.snapshots = [];
        state.snapshots2 = [];
        state.index = -1;
    },

    record(state, name) {

        let last = state.snapshots2[state.index];
        let now = JSON.stringify(poster.state.p);
        if (last === now) {
            console.warn('no any change to record!')
            return;
        } else {
            // console.info(now)
        }

        state.index++;
        console.info('record state.index=', state.index, 'name=', name)
        state.snapshots[state.index] = name;
        state.snapshots2[state.index] = JSON.stringify(poster.state.p);
        // 在 undo 过程中，添加新的快照时，要将它后面的快照清理掉
        if (state.index < state.snapshots.length - 1) {
            state.snapshots = state.snapshots.slice(0, state.index + 1)
            state.snapshots2 = state.snapshots2.slice(0, state.index + 1)
        }
    },

    undo(state) {
        if (state.index > 0) {
            state.index--;
            let p = JSON.parse(state.snapshots2[state.index]);
            p.key = uniqueId()  // 解决组件不重新渲染问题
            Vue.set(poster.state, 'p', p)
        }
    },

    redo(state) {
        if (state.index < state.snapshots.length - 1) {
            state.index++;
            let p = JSON.parse(state.snapshots2[state.index]);
            p.key = uniqueId()  // 解决组件不重新渲染问题
            Vue.set(poster.state, 'p', p)
        }
    },
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
}
