import _ from "lodash"

export default {

    state: () => ({
        pickingFor: null
    }),

    getters: {
        pickingFor(state) {
            return state.pickingFor;
        }
    },

    mutations: {

        setPickingFor(state, loop) {
            state.pickingFor = loop;
            if (loop != null) {
                loop.replacement = null;

            }
        },
        pair(state, { scaffoldLoop, insertLoop }) {
            scaffoldLoop.replacement = insertLoop;
        }
    },

    actions: {
        pickFor(context, loop) {
            if (loop.id == context.getters.pickingFor?.id) {
                context.commit('setPickingFor', null);
            } else {
                context.commit('setPickingFor', loop);

            }
        },
        selectPairingInsert(context, loop) {
            context.commit("pair", { scaffoldLoop: context.getters.pickingFor, insertLoop: loop });
            context.commit("setPickingFor", null);
        },
        removePairedInsert(context, loop) {
            context.commit("pair", { scaffoldLoop: loop, insertLoop: null });
            context.commit("setPickingFor", null);
        },

        async computeProteinLoopMatch(context, { staticProteinName, mobileProteinName }) {
            const api = context.getters.getApi;
            const static_chain = context.getters.getProtein(staticProteinName).chain;
            const mobile_chain = context.getters.getProtein(mobileProteinName).chain;

            let paired_loops_promise = api.post("/loop-pairing", {
                "static_name": staticProteinName,
                "static_chain": static_chain,
                "mobile_name": mobileProteinName,
                "mobile_chain": mobile_chain,
            })

            context.dispatch("addAwaitable", {
                id: _.uniqueId("awaiting"),
                promise: paired_loops_promise,
                description: "Pairing loops"
            });

            let pairedLoopsData = await paired_loops_promise;
            let pairs = pairedLoopsData.data.pairs;
            for (let scaffold_id in pairs) {
                let scaffoldLoop = context.getters.getWantedLoops.find(l => l.id == scaffold_id);
                if(scaffoldLoop == null){
                    //only pairing wanted loops
                    continue
                }
                // let scaffoldLoop = context.getters.getScaffold.loops.find(l => l.id.toUpperCase() == scaffold_id.toUpperCase())
                let insertLoop = context.getters.getInsert.loops.find(l => l.id.toUpperCase() == pairs[scaffold_id].toUpperCase())
                context.commit('pair', { scaffoldLoop, insertLoop })
            }


        },
    }
}