import _ from "lodash";
import * as d3 from "d3";

import { color } from "d3";
export default {
    state: {
        details: [],
        usedScaffoldColors: 0,
        usedInsertColors: 0,
        colorResolution: 4
    },
    getters: {
        getLoopDetails(state, getters, rootState) {
            return state.details;
        },

        getCompleteLoopDetails(state) {
            return state.details.filter(d => d.loop.hasGeometry)
        },

        getNextScaffoldColor(state, getters) {
            let originalColor = color(getters.getScaffold.color);
            return color(d3.scaleLinear()
                .domain([0, state.colorResolution])
                .range([originalColor.brighter(1.5), originalColor.darker(5)])(state.usedScaffoldColors));
        },

        getNextInsertColor(state, getters) {
            let originalColor = color(getters.getInsert.color);
            return color(d3.scaleLinear()
                .domain([0, state.colorResolution])
                .range([originalColor.brighter(1.5), originalColor.darker(5)])(state.usedInsertColors));
        }
    },
    mutations: {

        addLoopDetail(state, { detail, role }) {
            if (role == "scaffold") {
                detail.number = state.usedScaffoldColors;
                state.usedScaffoldColors = (state.usedScaffoldColors + 1) % state.colorResolution;
            } else {
                detail.number = state.usedInsertColors;
                state.usedInsertColors = (state.usedInsertColors + 1) % state.colorResolution;
            }
            state.details.push(detail);
        },
        removeLoopDetail(state, detail) {
            state.details = _.filter(state.details, (d) => d.protein.name != detail.protein.name || d.loop.id != detail.loop.id);
            detail.loop.color = null;
        },

    },
    actions: {
        addLoopDetail(context, detail) {
            if (_.filter(context.getters.getLoopDetails, (d) => d.protein.name == detail.protein.name && d.loop.id == detail.loop.id).length == 0) {
                let isScaffold = context.getters.getScaffold.name == detail.protein.name
                detail.loop.color = isScaffold
                    ? context.getters.getNextScaffoldColor
                    : context.getters.getNextInsertColor;
                context.commit("addLoopDetail", { detail, role: (isScaffold ? "scaffold" : "insert") });
            }
        },
        removeLoopDetailByLoop(contex, loop) {
            let detail = contex.getters.getLoopDetails.find(d => d.loop.id == loop.id);
            if (detail != null) {
                contex.commit("removeLoopDetail", detail);
            }
        }

    }
}