import React from 'react';
import {   connect } from 'react-redux'
import * as Shared from 'placeholder-shared'
import * as state from './state.js'

function getStepForOperation(operation) {
}

export function getInitialStepData(operationType, operation, name, stepCounterToAdd) {
	return {
		type: operationType,
		operation,
		inputs: {},
		outputs: {},
		name,
		stepCounter:stepCounterToAdd
	}
}

export function LoadSpecsThunk() {
	return function (dispatch, getState) {
		var currentState = getState()
		

	}
}
export function serializeTask(currentState) {
	var treeData = currentState['treeData']
	var newStepData = JSON.parse(JSON.stringify(currentState['stepsData']))
	var taskName = currentState['tasks'][currentState['currentTask']]['name']
	//console.log("Treedata before" , treeData)
	let serializeData =  {
		'treeData':treeData.serialize(),
		'stepsData':newStepData,
		'name':taskName
	}
	return serializeData
}

export function SaveAllThunk() {
	return function (dispatch, getState) {
		var currentState = getState()
		var serializedTask = serializeTask(currentState)
		console.log("serialized task", serializedTask)
		var query = {
			taskID:currentState['currentTask']
		}
		return new Promise((resolve,reject) => {
			Shared.Utils.apiPutJson("task", query, serializedTask).then((result) => {
				dispatch(state.getDirtyAction(true))
				resolve()
			})
		})
	}
}

export function PlayWorldThunk(onStepPlayed, onTaskPlayed) {
	return Shared.Runner.PlayWorldThunk(onStepPlayed, onTaskPlayed)
}

export function PlayAllThunkNoThrow(onRunResult) {
	return function(dispatch, getState) {
		let taskID = getState()['currentTask']
		var func = PlayAllThunk(taskID, onRunResult)
		return func(dispatch,getState).then((value) => {
		}).catch((error)=> {
				console.log("no throw error", error)
			})
	}
}
export function PlayAllThunk(taskID, onRunResult){
	return Shared.Runner.PlayTaskThunk(taskID,onRunResult)
}

export function PlayThunk(taskID, stepCounter, operation){
	return (dispatch, getState) => {
		const onRunResult = (stepCounter) => {

		}
		let context = Shared.Context.getContextForStep(getState, dispatch, null, onRunResult,stepCounter)
		Shared.Runner.PlayThunkInternal(taskID, stepCounter, context).then(function (result){ 
		}).catch((error) => {
			let errorDictionary = Shared.Runner.GetErrorDictionaryForPlayThunkInternal(error)
		})
	}
}
