<commit_before>/**
 * Created by ksinger on 19.02.2016.
 */

import  won from '../won-es6.js';
import Immutable from 'immutable';
import jsonld from 'jsonld'; //import *after* the rdfstore to shadow its custom jsonld

import {
    selectAllByConnectionUri,
    selectOpenConnectionUri,
    selectRemoteEvents,
} from '../selectors.js';

import {
    is,
    urisToLookupMap,
    msStringToDate,
    getIn,
    get,
    jsonld2simpleFormat,
    cloneAsMutable,
} from '../utils.js';

import {
   makeParams,
} from '../configRouting.js';

import {
    ensureLoggedIn,
} from './account-actions';

import {
    actionTypes,
    actionCreators,
} from './actions.js';

import {
    buildCreateMessage,
    buildOpenMessage,
    buildCloseMessage,
    buildChatMessage,
    buildRateMessage,
    buildConnectMessage,
    getEventsFromMessage,
} from '../won-message-utils.js';

export function connectionsChatMessage(chatMessage, connectionUri) {
   return dispatch => {
       console.log('connectionsChatMessage: ', chatMessage, connectionUri);

       buildChatMessage(chatMessage, connectionUri)
       .then(msgData => {

           /*
            * not sure how elegant it is to build the ld and then parse
            * it again. It uses existing utilities at least, reducing
            * redundant program logic. ^^
             */
           const optimisticEventPromise = getEventsFromMessage(msgData.message)
               .then(optimisticEvent => optimisticEvent['msg:FromOwner']);

           return Promise.all([
               Promise.resolve(msgData.message),
               optimisticEventPromise,
           ]);
       })
       .then( ([ message, optimisticEvent ]) => dispatch({
               type: actionTypes.connections.sendChatMessage,
               payload: {
                   eventUri: optimisticEvent.uri,
                   message,
                   optimisticEvent,
               }
           })
       )
   }
}

export function connectionsFetch(data) {
    return dispatch=> {
        const allConnectionsPromise = won.executeCrawlableQuery(won.queries["getAllConnectionUrisOfNeed"], data.needUri);
        allConnectionsPromise.then(function (connections) {
            console.log("fetching connections");
            dispatch(actionCreators.needs__connectionsReceived({needUri: data.needUri, connections: connections}));
            dispatch(actionCreators.events__fetch({connectionUris: connections}))
        })
    }
}

export function connectionsOpen(connectionUri, message) {
    return (dispatch, getState) => {
        buildOpenMessage(connectionUri, message)
        .then(msgData => {
            const optimisticEventPromise = getEventsFromMessage(msgData.message)
                .then(optimisticEvent => optimisticEvent['msg:FromOwner']);
            return Promise.all([
                Promise.resolve(msgData),
                optimisticEventPromise,
            ]);

            //TODO dispatch connections.open
        })
        .then( ([ msgData, optimisticEvent ]) => {
            // dispatch(actionCreators.messages__send(messageData));
            dispatch({
                type: actionTypes.connections.open,
                payload: {
                    eventUri: optimisticEvent.uri,
                    message: msgData.message,
                    optimisticEvent,
                }
            });

            dispatch(actionCreators.router__stateGoAbs("post", {
                postUri: optimisticEvent.hasSenderNeed,
                connectionType: won.WON.Connected,
                connectionUri: optimisticEvent.hasSender,
            }));

        });
    }
}


export function connectionsConnect(connectionUri, textMessage) {
    return async (dispatch, getState) => {
        const state = getState();
        const eventData = selectAllByConnectionUri(state, connectionUri).toJS(); // TODO avoid toJS; UPDATE TO NEW STRUCTURE
        const action = await buildConnectMessage(eventData.connection.uri, textMessage);

        dispatch(actionCreators.messages__send({eventUri: action.eventUri, message: action.message}));

        const framed = await jsonld.promises.frame(
            action.message,
            {
                '@id': action.eventUri,
                '@context': action.message['@context']
            }
        )

        let event = getIn(framed, ['@graph', 0]);
        if(event) {
            event['@context'] = framed['@context']; // context is needed by jsonld2simpleFormat for expanding prefixes in values
            event = jsonld2simpleFormat(event);
        }

        dispatch({
            type: actionTypes.connections.connect,
            payload: {
                connectionUri,
                textMessage,
                eventUri: action.eventUri,
                optimisticEvent: event,
            }
        });
    }
}

export function connectionsConnectAdHoc(theirNeedUri) {
    return (dispatch, getState) => {
        const state = getState();

        const theirNeed = getIn(state, ['needs', theirNeedUri]);
        const adHocDraft = generateResponseNeedTo(theirNeed);
        const nodeUri = getIn(state, ['config', 'defaultNodeUri']);

        ensureLoggedIn(dispatch, getState)
        .then(() => {
            const { message, eventUri, needUri } = buildCreateMessage(adHocDraft, nodeUri);
            return dispatch({
                type: actionTypes.needs.create, // TODO custom action
                payload: {eventUri, message, needUri}
            })

        })
        .then(() => {
            console.log('STARTED PUBLISHING AD HOC DRAFT: ', adHocDraft);

        });

<commit_msg>Building ad-hoc connect message.<commit_after>/**
 * Created by ksinger on 19.02.2016.
 */

import  won from '../won-es6.js';
import Immutable from 'immutable';
import jsonld from 'jsonld'; //import *after* the rdfstore to shadow its custom jsonld

import {
    selectAllByConnectionUri,
    selectOpenConnectionUri,
    selectRemoteEvents,
} from '../selectors.js';

import {
    is,
    urisToLookupMap,
    msStringToDate,
    getIn,
    get,
    jsonld2simpleFormat,
    cloneAsMutable,
} from '../utils.js';

import {
   makeParams,
} from '../configRouting.js';

import {
    ensureLoggedIn,
} from './account-actions';

import {
    actionTypes,
    actionCreators,
} from './actions.js';

import {
    buildCreateMessage,
    buildOpenMessage,
    buildCloseMessage,
    buildChatMessage,
    buildRateMessage,
    buildConnectMessage,
    buildAdHocConnectMessage,
    getEventsFromMessage,
} from '../won-message-utils.js';

export function connectionsChatMessage(chatMessage, connectionUri) {
   return dispatch => {
       console.log('connectionsChatMessage: ', chatMessage, connectionUri);

       buildChatMessage(chatMessage, connectionUri)
       .then(msgData => {

           /*
            * not sure how elegant it is to build the ld and then parse
            * it again. It uses existing utilities at least, reducing
            * redundant program logic. ^^
             */
           const optimisticEventPromise = getEventsFromMessage(msgData.message)
               .then(optimisticEvent => optimisticEvent['msg:FromOwner']);

           return Promise.all([
               Promise.resolve(msgData.message),
               optimisticEventPromise,
           ]);
       })
       .then( ([ message, optimisticEvent ]) => dispatch({
               type: actionTypes.connections.sendChatMessage,
               payload: {
                   eventUri: optimisticEvent.uri,
                   message,
                   optimisticEvent,
               }
           })
       )
   }
}

export function connectionsFetch(data) {
    return dispatch=> {
        const allConnectionsPromise = won.executeCrawlableQuery(won.queries["getAllConnectionUrisOfNeed"], data.needUri);
        allConnectionsPromise.then(function (connections) {
            console.log("fetching connections");
            dispatch(actionCreators.needs__connectionsReceived({needUri: data.needUri, connections: connections}));
            dispatch(actionCreators.events__fetch({connectionUris: connections}))
        })
    }
}

export function connectionsOpen(connectionUri, message) {
    return (dispatch, getState) => {
        buildOpenMessage(connectionUri, message)
        .then(msgData => {
            const optimisticEventPromise = getEventsFromMessage(msgData.message)
                .then(optimisticEvent => optimisticEvent['msg:FromOwner']);
            return Promise.all([
                Promise.resolve(msgData),
                optimisticEventPromise,
            ]);

            //TODO dispatch connections.open
        })
        .then( ([ msgData, optimisticEvent ]) => {
            // dispatch(actionCreators.messages__send(messageData));
            dispatch({
                type: actionTypes.connections.open,
                payload: {
                    eventUri: optimisticEvent.uri,
                    message: msgData.message,
                    optimisticEvent,
                }
            });

            dispatch(actionCreators.router__stateGoAbs("post", {
                postUri: optimisticEvent.hasSenderNeed,
                connectionType: won.WON.Connected,
                connectionUri: optimisticEvent.hasSender,
            }));

        });
    }
}


export function connectionsConnect(connectionUri, textMessage) {
    return async (dispatch, getState) => {
        const state = getState();
        const eventData = selectAllByConnectionUri(state, connectionUri).toJS(); // TODO avoid toJS; UPDATE TO NEW STRUCTURE
        const action = await buildConnectMessage(eventData.connection.uri, textMessage);

        dispatch(actionCreators.messages__send({eventUri: action.eventUri, message: action.message}));

        const framed = await jsonld.promises.frame(
            action.message,
            {
                '@id': action.eventUri,
                '@context': action.message['@context']
            }
        )

        let event = getIn(framed, ['@graph', 0]);
        if(event) {
            event['@context'] = framed['@context']; // context is needed by jsonld2simpleFormat for expanding prefixes in values
            event = jsonld2simpleFormat(event);
        }

        dispatch({
            type: actionTypes.connections.connect,
            payload: {
                connectionUri,
                textMessage,
                eventUri: action.eventUri,
                optimisticEvent: event,
            }
        });
    }
}

export function connectionsConnectAdHoc(theirNeedUri) {
    return async (dispatch, getState) => {
        const state = getState();

        const theirNeed = getIn(state, ['needs', theirNeedUri]);
        const adHocDraft = generateResponseNeedTo(theirNeed);
        const nodeUri = getIn(state, ['config', 'defaultNodeUri']);

        await ensureLoggedIn(dispatch, getState);

        const { message, eventUri, needUri } = buildCreateMessage(adHocDraft, nodeUri);
        dispatch({
            type: actionTypes.needs.create, // TODO custom action
            payload: {eventUri, message, needUri}
        });

        const cnctMsg = buildAdHocConnectMessage(needUri)

        console.log('STARTED PUBLISHING AD HOC DRAFT: ', adHocDraft);



{'fraction_non_alphanumeric': 0.10188880021282255, 'fraction_numerical': 0.002305577724572138, 'mean_word_length': 2.164421997755331, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '20096', 'n_tokens_mistral': 2984, 'n_tokens_neox': 2831, 'n_words': 612}