'use strict';
/**
 * @ngdoc controller
 * @name AddMacroRoomController
 * @description
 *  room 선택 화면
 */
app.controller('AddMacroRoomController', function ($scope, $state, toastr, Systems) {
	$scope.system = Systems.getCurrentSystem();


	$scope.doNext = function() {
		// room 정보 얻어와서 저장
		return Systems.updateRoomDevices($scope.addMacro.room.id)
		.then(function(data) {
			var roomDevices = Systems.getRoomDevices();
			$scope.addMacro.room.devices = roomDevices.devices;

			// dev_type이 twoway(1)인 device를 모두 제거하는 과정에서 $scope.addMacro.room.devices 에서 SNP-2 가 제거되는데 SNP-2 가 있는 목록이 "Add jump to" 에서 필요해서 copy 를 만듬
			$scope.addMacro.room.devicesAndSNP2 = angular.copy(roomDevices.devices);

			// twoway_devices 중 TRF-ZW 추가한 device 목록 생성
			$scope.addMacro.room.allDevices = angular.copy($scope.addMacro.room.devices);

			_.each($scope.system.rooms, function(room) {
				var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
				if (trfzw) {
					if (!trfzw.data) {
						trfzw.data = [];
					}
					$scope.addMacro.room.allDevices.push(trfzw);

					return false;
				}
			});

			$state.go('menu.advanced.add-macros.macro-type');
		})
		.catch(toastr.error);
	};
});

/**
 * @ngdoc controller
 * @name MacroTypeController
 * @description
 *  macro type 선택 화면
 */
app.controller('MacroTypeController', function ($rootScope, $scope, $state, toastr, Systems) {
  // Advanced Menu 의 Automate activities on the Entertainment Menu 메뉴를 클릭해서 들어온 경우
  // Programming Menu 의 Setup a simple activity 메뉴에서 넘어온 경우.
  //   => currentRoom 을 선택된 room 으로 설정함
  if (!$scope.addMacro.room.id) {
    var currentRoomId,
      timer;

    // currentRoom 이 설정되었는지 0.1초에 한번씩 확인
    timer = setInterval(function() {
      currentRoomId = Systems.getCurrentRoom();

      if (currentRoomId) {
        clearInterval(timer);

        $scope.addMacro.room = _.findWhere($scope.system.rooms, {
          id: currentRoomId
        });
        console.log('room', $scope.addMacro.room);

        // 아래의 코드는 AddMacroRoomController 의 doNext 에서 하는 동작임
        Systems.updateRoomDevices($scope.addMacro.room.id)
          .then(function(data) {
            var roomDevices = Systems.getRoomDevices();
            $scope.addMacro.room.devices = roomDevices.devices;

            // dev_type이 twoway(1)인 device를 모두 제거하는 과정에서 $scope.addMacro.room.devices 에서 SNP-2 가 제거되는데 SNP-2 가 있는 목록이 "Add jump to" 에서 필요해서 copy 를 만듬
            $scope.addMacro.room.devicesAndSNP2 = angular.copy(roomDevices.devices);

            // twoway_devices 중 TRF-ZW 추가한 device 목록 생성
            $scope.addMacro.room.allDevices = angular.copy($scope.addMacro.room.devices);

            _.each($scope.system.rooms, function(room) {
              var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
              if (trfzw) {
                if (!trfzw.data) {
                  trfzw.data = [];
                }
                $scope.addMacro.room.allDevices.push(trfzw);

                return false;
              }
            });

            $state.go('menu.advanced.add-macros.macro-type');
          })
          .catch(toastr.error);
      }
    }, 100);
  }

	var steps = $scope.addMacro.steps;
	while(steps.length > 0) {
		steps.pop();
	}
	$scope.addMacro.currentDevice = {};
	$scope.addMacro.button = {};
	$scope.addMacro.doneScreen = {'index': 0,'device': {}, 'devices': []};
	$scope.addMacro.disablePopup = false;

	$scope.navigateTo = function(state) {

		var base = 'menu.advanced.add-macros';
		switch (state) {
			case 'Turn Off All':
				$scope.macroType.id = 0;
				// 해당 room 의 power macro 데이터 얻어와서 저장
				Systems.updateCurrentMacroForPower($scope.addMacro.room.id).then( function(data) {
					console.log(data);
					$state.go(base + '.finish');
				}).catch(toastr.error);

				break;
			case 'Device Activity':
				$scope.macroType.id =  1;
				$state.go(base + '.choose-device');
				break;
			case 'Custom Button':
				$scope.macroType.id = 2;
				$state.go(base + '.button-name');
				break;
			case 'Scheduled Event':
				$scope.macroType.id = 3;
				$state.go(base + '.button-name');
				break;
			default:
				//do nothing
		}
	};

});

/**
 * @ngdoc controller
 * @name ButtonNameController
 * @description
 *  entertainment page button 생성할 button name 입력 화면
 */
app.controller('ButtonNameController', function ($scope, $state) {
	$scope.doNext = function() {
		$state.go('menu.advanced.add-macros.finish');
	};
});

/**
 * @ngdoc controller
 * @name ChooseMacroDeviceController
 * @description
 *  entertainment page device 생성할 device 선택 화면
 */
app.controller('ChooseMacroDeviceController', function ($scope, $state) {
	$scope.doNext = function() {
		$state.go('menu.advanced.add-macros.finish');
	};
});

/**
 * @ngdoc controller
 * @name FinishMacroController
 * @description
 *  macro device, commands 입력
 */
app.controller('FinishMacroController', function ($scope, $timeout, $state, $modal, toastr, Rooms, Devices, Systems) {
	var scheEventData = Rooms.getScheEventData();

	function isJsonString(str) {
		try {
			JSON.parse(str);
		} catch (e) {
			return false;
		}
		return true;
	}

	$scope.isJsonString = isJsonString;

	function cleanUp(type, roomId, arr) {
		console.log('cleanUp-arr=', arr);
		var filteredSteps = [];
		var steps =  isJsonString(arr) ? JSON.parse(arr):arr ;
		_.forEach(steps, function (step) {
			var device;
			var variable;

			if (type === 'macro') {
				if (step.type === 1) {
					device = Systems.getDevice(roomId, step.device_id);
					if (device) {
						step.name = device.name + ': ' + _.find(device.funcs, {'id': step.func}).name;
						filteredSteps.push(step);
					}
				} else if (step.type === 2) {
					step.name = 'Delay ' + step.value/1000 + ' seconds';
					filteredSteps.push(step);
				} else if (step.type === 3 && step.to.type === 1) {
					device = Systems.getDevice(roomId, step.to.value);
					if (device) {
						step.name = 'Jump to ' + device.name;
						filteredSteps.push(step);
					}
				} else if (step.type === 4) {
					variable = _.find($scope.system.variables, {'id': step.cond.id});
					if (variable) {
						if(variable.type == 0){
							name = 'If: ' + variable.name + ', ' + (step.cond.value == 1 ? 'True':'False');
						} else{
							name = 'If: ' + variable.name + ' ' +  step.cond.operate + ' ' + step.cond.value;
						} 

						step.name = name;

						step.steps = [{name:'True', steps:[]}, {name:'False', steps:[]}];

						filteredSteps.push(step);

						if(step.true){
							step.steps[0].steps = cleanUp('macro', roomId, step.true);
						}

						if(step.false){
							step.steps[1].steps = cleanUp('macro', roomId, step.false);
						}
					}
				}
				else if (step.type === 5) {
					variable = _.find($scope.system.variables, {'id': step.id});
					if (variable) {
						var dispValue = step.value;
						if(variable.type == 0){
							if(step.value == 0){
								dispValue = 'false' ;
							}
							else if(step.value == 1){
								dispValue = 'true' ;
							}
							else if(step.value == 2){
								dispValue = 'invert' ;
							}
						}

						step.name = 'VAR ' + variable.name + '= ' + dispValue;
						filteredSteps.push(step);
					}
				} else if (step.type === 16) {
					_.each($scope.system.rooms, function(room) {
						device = _.find(room.twoway_devices, {model: 'TRF-ZW1'});

						if (device) {
							var scene = _.find(device.data, {id: step.id});

							if (scene) {
								step.name = 'S : ' + scene.name + ' (' + scene.room + ')';
								filteredSteps.push(step);
							}

							return false;
						}
					});
				}
			} else {
				device = Systems.getDevice(roomId, step.device_id);
				if (device) {
					step.name = device.name;
					step.funcs = device.funcs;
					filteredSteps.push(step);
				}

			}
		});
		return filteredSteps;
	}

	// scheduled event 수정하러 들어온 경우
	if (scheEventData) {
		$scope.addMacro.room = scheEventData.room;
		$scope.addMacro.steps = cleanUp('macro', $scope.addMacro.room.id, scheEventData.event.macro);
		$scope.addMacro.button.name = scheEventData.event.display_text;
		$scope.addMacro.disablePopup = false;
		$scope.addMacro.doneScreen.index = 0;
		$scope.addMacro.doneScreen.devices = [];

		$scope.macroType.id = 3;

		// room 정보 얻어와서 저장
		Systems.updateRoomDevices($scope.addMacro.room.id)
			.then(function(data) {
				var roomDevices = Systems.getRoomDevices();
				$scope.addMacro.room.devices = roomDevices.devices;

				// dev_type이 twoway(1)인 device를 모두 제거하는 과정에서 $scope.addMacro.room.devices 에서 SNP-2 가 제거되는데 SNP-2 가 있는 목록이 "Add jump to" 에서 필요해서 copy 를 만듬
				$scope.addMacro.room.devicesAndSNP2 = angular.copy(roomDevices.devices);

				///dev_type이 twoway(1)인 device를 모두 제거.
				var item = null;
				while(item = _.where($scope.addMacro.room.devices, {'dev_type': 1})[0]) {
					var idx = $scope.addMacro.room.devices.indexOf(item);
					$scope.addMacro.room.devices.splice(idx, 1);
				}

				// twoway_devices 중 TRF-ZW 추가한 device 목록 생성
				$scope.addMacro.room.allDevices = angular.copy($scope.addMacro.room.devices);

				var system = Systems.getCurrentSystem();
				_.each(system.rooms, function(room) {
					var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
					if (trfzw) {
						if (!trfzw.data) {
							trfzw.data = [];
						}
						$scope.addMacro.room.allDevices.push(trfzw);

						return false;
					}
				});
			})
			.catch(toastr.error);
	}


	$scope.remove = function(scope) {
		scope.remove();
	};

	$scope.options = {
		accept: function(sourceNodeScope, destNodesScope, destIndex) {
			//console.log('sourceNodeScope=', sourceNodeScope);
			//console.log('destNodesScope=', destNodesScope);
			if (sourceNodeScope.$modelValue.type == null || destNodesScope.nodropEnabled || destNodesScope.outOfDepth(sourceNodeScope)) {
				return false;
			}

	        var subDepth = 0;
	        function countSubDepth(scope) {
				var i, childNodesScope,
					count = 0,
					nodes = scope.childNodes();

				//console.log('childNodes=', nodes);

				for (i = 0; i < nodes.length; i++) {
					childNodesScope = nodes[i].$childNodesScope;

					if (childNodesScope && childNodesScope.childNodesCount() > 0) {
						count = 1;
						countSubDepth(childNodesScope);
					}
				}
				subDepth += count;				
			}

			var maxSubDepth = function (scope) {
				subDepth = 0;
				if (scope.hasChild()) {
					countSubDepth(scope.$childNodesScope);
					subDepth++;
				}
				return subDepth;
			};

			/*
			console.log('sourceNodeScope.childNodes()=', sourceNodeScope.childNodes());
			console.log('sourceNodeScope.childNodesCount()=', sourceNodeScope.childNodesCount());
			console.log('maxSubDepth(sourceNodeScope)=', maxSubDepth(sourceNodeScope));
			console.log('destNodesScope.depth()=', destNodesScope.depth());
			console.log('destNodesScope.maxDepth=', destNodesScope.maxDepth);
			console.log('destNodesScope.$treeScope.maxDepth=', destNodesScope.$treeScope.maxDepth);
			*/			

			//angular-ui-tree module의 maxSubDepth function에서 sub depth count를 child node 존재 유무를 기준으로 함.
			//그래서 2depth인 tree인 경우 depth count를 0으로 return하여 outOfDepth function을 호출해도 제대로된 결과를 받지 못하고,
			// (max-depth -1) depth인 tree에 2depth의 tree를 drag/drop하면 삽입이 됨.
			//그래서, 별도의 maxSubDepth function을 구현함.
			var sumDepth =  (maxSubDepth(sourceNodeScope)+1) + destNodesScope.depth();
			var maxDepth = destNodesScope.maxDepth || destNodesScope.$treeScope.maxDepth;

			if(sumDepth  > maxDepth){
				return false;
			}

			return true;
		},
	};

	var getRootNodesScope = function() {
		return angular.element(document.getElementById("tree-root")).scope();
	};

	$scope.collapseAll = function() {
		var scope = getRootNodesScope();
		scope.collapseAll();
	};

	$scope.expandAll = function() {
		var scope = getRootNodesScope();
		scope.expandAll();
	};


	$scope.addStep = function (device, func, twowayDevice) {
		if (twowayDevice) {
			return {'name': 'S : ' + func.name + ' (' + func.room + ')', 'type': 16, 'sub_type': 'scene', 'id': func.id, 'cmd': 1 };		// 1 : Activate, 2 : Deactivate
		} else {
			return {'name': device.name + ': ' + func.name, 'type': 1, 'device_id': device.id, 'func': func.id };
		}
	};

	$scope.deleteAll = function() {
		var arr = $scope.addMacro.steps;
		while(arr.length > 0) {
			arr.pop();                     
		}
	};

	$scope.goBack = function() {
		if ($scope.macroType.id === 1) {
			$state.go('menu.advanced.add-macros.choose-device');
		} else if ($scope.macroType.id === 2) {
			$state.go('menu.advanced.add-macros.button-name');
		} else {
			$state.go('menu.advanced.add-macros.macro-type');
		}
	};

	$scope.doNext = function() {
		if ($scope.macroType.id === 3) {
			$state.go('menu.advanced.add-macros.macro-schedule');
		} else {
			$state.go('menu.advanced.add-macros.macro-done');
		}
	};

	$scope.refreshScenes = function(device) {
		Devices.updateTwowayDevice($scope.addMacro.room.id, device.id)
			.then(function(data) {
				console.log(data);

				var item = _.where($scope.addMacro.room.allDevices, {'id': device.id})[0];
				item.data = data;
			}, function() {
				var modal = $modal({
					scope: $scope,
					title: "Couldn't refresh the list",
					container: '.editor-container',
					template: 'views/modal-tpls/refresh-the-list.html',
					show: false
				});

				modal.$promise.then(modal.show);
			})
			.catch(toastr.error);
	};

});

/**
 * @ngdoc controller
 * @name MacroDoneController
 * @description
 *  macro 설정 완료 화면
 */
app.controller('MacroDoneController', function ($scope, $state, toastr, Systems) {
	$scope.addMacro.doneScreen.index = 0;

	$scope.goBack = function() {
		$state.go('menu.advanced.add-macros.finish');
	};

	function cleanUp(steps) {
		var filteredSteps = steps;
		_.forEach(filteredSteps, function (step) {
			delete step.name; 
			if(step.type == 4){
				console.log('cleanUp-step=', step);
				if(0 < step.steps[0].steps.length) {						
					step.steps[0].steps = cleanUp(step.steps[0].steps);
					step.true = angular.copy(step.steps[0].steps);					
				}
				if(0 < step.steps[1].steps.length) {
					step.steps[1].steps = cleanUp(step.steps[1].steps);
					step.false = angular.copy(step.steps[1].steps);					
				}
				delete step.steps;
			}
		});
		return filteredSteps;
	}

	$scope.doNext = function() {
		if ($scope.addMacro.disablePopup) {
			var steps =  angular.copy($scope.addMacro.steps);
			steps = cleanUp(steps);
			console.log('steps=', steps);

			//var autoWait = $scope.addMacro.autoWait ? 1:0;
			var jsonData = JSON.stringify( { auto_wait: 1 , edit_type: 1, popup: 0, activity: [], macro: steps } );
			console.log('jsonData=', jsonData);

			var handleSuccess = function(response) {
				if(response.data.result === true) {
					$state.go('menu.advanced.add-macros.next-action');
				} else {
					toastr.error('Your edit/create action failed.  Please try again.');
				}
			};

			var handleError = function(error){
				toastr.error("Please try again");
			};

			if ($scope.macroType.id === 0) {
				// 해당 room 의 power macro 데이터 저장
				Systems.storePowerMacro($scope.addMacro.room.id, jsonData).then(handleSuccess, handleError);
			} else if ($scope.macroType.id === 1) {
				// 해당 device ID 와 연계된 button 의 데이터 저장
				Systems.storeDeviceButtonMacro($scope.addMacro.room.id, $scope.addMacro.currentDevice.id, jsonData).then(handleSuccess, handleError);
			} else if ($scope.macroType.id === 2) {
				jsonData = { "text": $scope.addMacro.button.name, "auto_wait": 1 , "edit_type": 1, "popup": 0, "activity": [], "macro": steps } ;
				// button 생성
				Systems.createCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, jsonData).then(handleSuccess, handleError);
			}
		} else {
			$state.go('menu.advanced.add-macros.macro-commands');
		}
	};

});

/**
 * @ngdoc controller
 * @name MacroScheduleController
 * @description
 *  macro schedule 설정 화면
 */
app.controller('MacroScheduleController', function ($scope, $state, toastr, Rooms, Systems) {
	var scheEventData = Rooms.getScheEventData();

	// scheduled event 수정하러 들어온 경우
	if (scheEventData) {
		$scope.scheduledEvent = {
			option: scheEventData.event.option,
			day_week: scheEventData.event.day_week,
			time: scheEventData.event.time
		};
	}

	var i,
		temp,
		temp2;

	if (!$scope.scheduledEvent.option) {
		$scope.scheduledEvent.option = 0;
	}
	if (!$scope.scheduledEvent.day_week) {
		$scope.scheduledEvent.day_week = 0;
	}
	if (!$scope.scheduledEvent.time) {
		$scope.scheduledEvent.hour = '01';
		$scope.scheduledEvent.minute = '00';
		$scope.scheduledEvent.ampm = 'AM';
	} else {
		temp = $scope.scheduledEvent.time.split(':');

		if (+temp[0] > 12) {
			$scope.scheduledEvent.hour = '' + (+temp[0] - 12);
			if (+$scope.scheduledEvent.hour < 10) {
				$scope.scheduledEvent.hour = '0' + $scope.scheduledEvent.hour;
			}

			$scope.scheduledEvent.ampm = 'PM';
		} else if (+temp[0] == 12) {
			$scope.scheduledEvent.hour = '' + temp[0];
			$scope.scheduledEvent.ampm = 'PM';
		} else if (+temp[0] == 0) {
			$scope.scheduledEvent.hour = '12';
			$scope.scheduledEvent.ampm = 'AM';
		} else {
			$scope.scheduledEvent.hour = '' + temp[0];
			$scope.scheduledEvent.ampm = 'AM';
		}
		$scope.scheduledEvent.minute = '' + temp[1];
	}

	$scope.scheduledEvent.hours = [];
	$scope.scheduledEvent.minutes = [];

	for (i = 1; i <= 12; i++) {
		if (i < 10) {
			$scope.scheduledEvent.hours.push('0' + i)
		} else {
			$scope.scheduledEvent.hours.push('' + i);
		}
	}

	for (i = 0; i < 60; i++) {
		if (i < 10) {
			$scope.scheduledEvent.minutes.push('0' + i)
		} else {
			$scope.scheduledEvent.minutes.push('' + i);
		}
	}

	$scope.scheduledEvent.day = {
		'sun': 0,
		'mon': 0,
		'tue': 0,
		'wed': 0,
		'thu': 0,
		'fri': 0,
		'sat': 0
	};

	if ($scope.scheduledEvent.day_week !== 0) {
		temp2 = +$scope.scheduledEvent.day_week;

		if (temp2 === 127) {
			$scope.scheduledEvent.everyday = true;
		} else {
			if (temp2 >= 64) {
				$scope.scheduledEvent.day.sat = '64';
				temp2 -= 64;
			}
			if (temp2 >= 32) {
				$scope.scheduledEvent.day.fri = '32';
				temp2 -= 32;
			}
			if (temp2 >= 16) {
				$scope.scheduledEvent.day.thu = '16';
				temp2 -= 16;
			}
			if (temp2 >= 8) {
				$scope.scheduledEvent.day.wed = '8';
				temp2 -= 8;
			}
			if (temp2 >= 4) {
				$scope.scheduledEvent.day.tue = '4';
				temp2 -= 4;
			}
			if (temp2 >= 2) {
				$scope.scheduledEvent.day.mon = '2';
				temp2 -= 2;
			}
			if (temp2 >= 1) {
				$scope.scheduledEvent.day.sun = '1';
				temp2 -= 1;
			}
		}
	}

	function generateTime() {
		if ($scope.scheduledEvent.ampm == 'PM' && $scope.scheduledEvent.hour == '12') {
			return '12:' + $scope.scheduledEvent.minute + ':00';
		} else if ($scope.scheduledEvent.ampm == 'AM' && $scope.scheduledEvent.hour == '12') {
			return '00:' + $scope.scheduledEvent.minute + ':00';
		} else if ($scope.scheduledEvent.ampm == 'PM') {
			return (+$scope.scheduledEvent.hour + 12) + ':' + $scope.scheduledEvent.minute + ':00';
		} else {
			return $scope.scheduledEvent.hour + ':' + $scope.scheduledEvent.minute + ':00';
		}
	}

	$scope.goBack = function() {
		$state.go('menu.advanced.add-macros.finish');
	};

	function cleanUp(steps) {
		var filteredSteps = steps;
		_.forEach(filteredSteps, function (step) {
			delete step.name; 
			if(step.type == 4){
				console.log('cleanUp-step=', step);
				if(0 < step.steps[0].steps.length) {						
					step.steps[0].steps = cleanUp(step.steps[0].steps);
					step.true = angular.copy(step.steps[0].steps);					
				}
				if(0 < step.steps[1].steps.length) {
					step.steps[1].steps = cleanUp(step.steps[1].steps);
					step.false = angular.copy(step.steps[1].steps);					
				}
				delete step.steps;
			}
		});
		return filteredSteps;
	}

	$scope.doNext = function() {
		$scope.scheduledEvent.day_week = 0;

		var days = _.values($scope.scheduledEvent.day);

		if ($scope.scheduledEvent.everyday) {
			$scope.scheduledEvent.day_week = 127;
		} else {
			_.each(days, function(day) {
				$scope.scheduledEvent.day_week += +day;
			});
		}

		$scope.scheduledEvent.time = generateTime();

		var steps =  angular.copy($scope.addMacro.steps);
		steps = cleanUp(steps);
		console.log('steps=', steps);

		var	systemId = Systems.getCurrentSystem().id,
			data = {
				display_text: $scope.addMacro.button.name,
				image_name: '' ,
				macro: steps,
				default_state: 1,
				option: $scope.scheduledEvent.option,
				day_week: $scope.scheduledEvent.day_week,
				time: $scope.scheduledEvent.time
			},
			jsonData;

		if (scheEventData) {
			data.id = scheEventData.event.id;
		}

		jsonData = JSON.stringify( data )
		console.log('jsonData=', jsonData);

		// scheduled event 수정
		if (scheEventData) {
			Rooms.setScheduledEventMacro(systemId, $scope.addMacro.room.id, jsonData).then(function(response) {
				if(response.data.result === true) {
					Systems.updateSystem(systemId).then(function () {
						Rooms.setScheEventData(null);
						$state.go('menu.advanced.add-macros.next-action');
					});
				} else {
					toastr.error('Your edit/create action failed.  Please try again.');
				}
			}, function(error){
				toastr.error("Please try again");
			});
		}
		// scheduled event 생성
		else {
			Rooms.createScheduledEventMacro(systemId, $scope.addMacro.room.id, jsonData).then(function(response) {
				if(response.data.result === true) {
					Systems.updateSystem(systemId).then(function () {
						Rooms.setScheEventData(null);
						$state.go('menu.advanced.add-macros.next-action');
					});
				} else {
					toastr.error('Your edit/create action failed.  Please try again.');
				}
			}, function(error){
				toastr.error("Please try again");
			});
		}
	};

});


app.controller('MacroCommandsController', function ($scope, $state, toastr, Systems) {

	$scope.goBack = function() {
		if ($scope.addMacro.doneScreen.index === 0) {
			$state.go('menu.advanced.add-macros.macro-done' );
		} else {
			$scope.addMacro.doneScreen.index--;
		}
	};

	function cleanUp(steps) {
		var filteredSteps = steps;
		_.forEach(filteredSteps, function (step) {
			delete step.name; 
			if(step.type == 4){
				console.log('cleanUp-step=', step);
				if(0 < step.steps[0].steps.length) {						
					step.steps[0].steps = cleanUp(step.steps[0].steps);
					step.true = angular.copy(step.steps[0].steps);					
				}
				if(0 < step.steps[1].steps.length) {
					step.steps[1].steps = cleanUp(step.steps[1].steps);
					step.false = angular.copy(step.steps[1].steps);					
				}
				delete step.steps;
			}
		});
		return filteredSteps;
	}

	$scope.doNext = function() {
		var len = $scope.addMacro.doneScreen.devices.length;
		if ($scope.addMacro.doneScreen.index + 1 === len) {

			//var autoWait = $scope.addMacro.autoWait ? 1:0;
			var steps =  angular.copy($scope.addMacro.steps);
			steps = cleanUp(steps);
			console.log('steps=', steps);

			var activityData = angular.copy($scope.addMacro.doneScreen.devices);

			_.forEach(steps, function(step) { delete step.name; });
			_.forEach(activityData, function(activity) {
				activity.func = activity.func.id;
				delete activity.name;
				delete activity.repeat_min;
				delete activity.repeat_macro;
				delete activity.target_type;
				delete activity.target_addr;
				delete activity.target_port;
				delete activity.funcs;
			});

			var jsonData = JSON.stringify( { auto_wait: 1 , edit_type: 1, popup: 1, activity: activityData, macro: steps } );
			console.log(jsonData);

			var handleSuccess = function(response) {
				if(response.data.result === true) {
					$state.go('menu.advanced.add-macros.next-action');
				} else {
					toastr.error('Your edit/create action failed.  Please try again.');
				}
			};

			var handleError = function(error){
				toastr.error("Please try again");
			};

			if ($scope.macroType.id === 0) {
				// 해당 room 의 power macro 데이터 저장
				Systems.storePowerMacro($scope.addMacro.room.id, jsonData).then(handleSuccess, handleError);
			} else if ($scope.macroType.id === 1) {
				// 해당 device ID 와 연계된 button 의 데이터 저장
				Systems.storeDeviceButtonMacro($scope.addMacro.room.id, $scope.addMacro.currentDevice.id, jsonData).then(handleSuccess, handleError);
			} else if ($scope.macroType.id === 2) {
				jsonData = JSON.stringify( { text: $scope.addMacro.button.name, auto_wait: 1 , edit_type: 1, popup: 1, activity: activityData, macro: steps } );
				// button 생성
				Systems.createCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, jsonData).then(handleSuccess, handleError);
			}
		} else {
			$scope.addMacro.doneScreen.index++;
		}

	};
});

