'use strict';
/**
 * @ngdoc controller
 * @name MainMenuLayoutController
 * @description
 *  entertainment main screen layout 편집 화면
 */
app.controller('MainMenuLayoutController', function ($rootScope, $scope, $state, $filter, $timeout, toastr, Rooms, Systems, Devices) {
	// scheduled event 기능을 eng, alpha 버전에서만 보이게 하기 위한 처리
	if ($rootScope.version.substr(-1) === 'e' || $rootScope.version.substr(-1) === 'a') {
		$scope.isAlpha = true;
	} else {
		$scope.isAlpha = false;
	}

	$scope.mainMenu.changingIcon = false;
	$scope.mainMenu.mainDevice.btns = [];
	$scope.mainMenu.mainDevice.id = Systems.getMainDevice().id;

	$scope.mainMenu.showBtnsType = 'devices';  // devices/events

	// icon 목록이 있는 json 파일로부터 데이터 얻기
	Devices.getInfoJson().success(function (data) {
		Devices.setIcons(data);
		$scope.mainMenu.deviceIcons = Devices.getIcons();

		console.log($scope.mainMenu.deviceIcons);
	}).error(function () {

	});

	// (1) mainDevice btns

	var btnIndexOffset = 0;

	_.forEach(Systems.getMainDevice().pages, function(page) {
		 _.forEach(page.btns, function(btn) {
			console.log(btn);
			btn.hidden_option = btn.hidden_option ? true:false;
			btn.hidden = btn.hidden ? true:false;
			btn.page_btn_idx += btnIndexOffset;
			$scope.mainMenu.mainDevice.btns.push(btn);
		 });
		 btnIndexOffset += 6;
	});

	$scope.mainMenu.mainDevice.btns = _($scope.mainMenu.mainDevice.btns).sortBy('page_btn_idx').value();
	console.log($scope.mainMenu.mainDevice.btns);

	$scope.deleteDevice = function (btn) {
		_.remove($scope.mainMenu.mainDevice.btns, { id: btn.id });
	};

	$scope.makeCopy = function(obj) {
		return angular.copy(obj);
	};

	$scope.isEmpty = function(obj) {
		return _.isEmpty(obj);
	};


	$scope.switchToImageView = function() {
		$scope.mainMenu.selectedImgName = angular.copy($scope.mainMenu.selectedBtn.image_name);
		$scope.mainMenu.changingIcon = true;
	};
	
	$scope.saveImage = function() {
		$scope.mainMenu.selectedBtn.image_name = angular.copy($scope.mainMenu.selectedImgName);
		$scope.mainMenu.changingIcon = false;
	};

	$scope.replaceButton = function (btnId) {
		var idx = _.findIndex($scope.mainMenu.mainDevice.btns, {'id': btnId});
		$scope.mainMenu.mainDevice.btns[idx] = $scope.mainMenu.selectedBtn;
	};

	$scope.clearSelectedBtn = function() {
		$timeout(function() {
				$scope.mainMenu.selectedBtn = {};
		}, 200);
	};

	// (2) scheduled events

	// scheduled event 목록 얻기
	Rooms.getEvents(Systems.getCurrentSystem().id, $scope.mainMenu.room.id).then(function(data) {
		$scope.mainMenu.scheEvents = data;

    _.forEach($scope.mainMenu.scheEvents, function(event) {
      event.hidden_option = event.hidden_option ? true:false;
      event.hidden = event.hidden ? true:false;
    });
	}).catch(function(error) {
		alert(error);
	});

	$scope.deleteEvent = function (event) {
		_.remove($scope.mainMenu.scheEvents, { id: event.id });

		var jsonData = JSON.stringify({ id: event.id });

		Rooms.deleteEvent(Systems.getCurrentSystem().id, $scope.mainMenu.room.id, jsonData)
			.then(function(data) {
				Systems.updateSystem(Systems.getCurrentSystem().id);
			})
			.catch(toastr.error);
	};

	$scope.switchToEventImageView = function() {
		$scope.mainMenu.selectedEventImgName = angular.copy($scope.mainMenu.selectedEvent.image_name);
		$scope.mainMenu.changingEventIcon = true;
	};

	$scope.saveEventImage = function() {
		$scope.mainMenu.selectedEvent.image_name = angular.copy($scope.mainMenu.selectedEventImgName);
		$scope.mainMenu.changingEventIcon = false;
	};

	$scope.replaceEvent = function (eventId) {
		var idx = _.findIndex($scope.mainMenu.scheEvents, {'id': eventId});
		$scope.mainMenu.scheEvents[idx] = $scope.mainMenu.selectedEvent;
	};

	$scope.clearSelectedEvent = function() {
		$timeout(function() {
			$scope.mainMenu.selectedEvent = {};
		}, 200);
	};

	// (3) 공통

	$scope.finish = function() {
		if ($scope.mainMenu.showBtnsType === 'devices') {
			var numPages = Math.ceil($scope.mainMenu.mainDevice.btns.length / 6);
			var pages = [];

			for (var pageId = 0; pageId < numPages; pageId++ ) {
				var page = {id: pageId};
				var start = pageId * 6;

				page.btns = $scope.mainMenu.mainDevice.btns.slice(start, start+6);
				for (var index = 0; index < page.btns.length; index++) {
					page.btns[index].page_btn_idx = index;
					page.btns[index].hidden_option = page.btns[index].hidden_option ? 1 : 0;
					page.btns[index].hidden = page.btns[index].hidden ? 1 : 0;
					console.log('finish- page.btn=', page.btns[index])
				}
				pages.push(page);
			}
			console.log(pages);

			Systems.setMainDevice({id: $scope.mainMenu.mainDevice.id, pages: pages});

			// main device 정보 서버에 저장
			Systems.storeMainDevice($scope.mainMenu.room.id).then(function(data) {
				// system 정보 얻어와서 저장
				Systems.updateSystem(Systems.getCurrentSystem().id).then(
					function (data) {
						console.log(data);
						$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
					},
					function (error) {
						alert(error);
					}
				);

			}, function(error) {
				alert(error);
			});
		} else if ($scope.mainMenu.showBtnsType === 'events') {
			_.forEach($scope.mainMenu.scheEvents, function(event, i) {
				event.hidden_option = event.hidden_option ? 1 : 0;
				event.hidden = event.hidden ? 1 : 0;
				event.order = i;
			});

			var jsonData = JSON.stringify({data: $scope.mainMenu.scheEvents});

			Rooms.storeEvents(Systems.getCurrentSystem().id, $scope.mainMenu.room.id, jsonData).then(function(data) {
				Systems.updateSystem(Systems.getCurrentSystem().id).then(
					function (data) {
						console.log(data);
						$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
					},
					function (error) {
						alert(error);
					}
				);
			}, function(error) {
				alert(error);
			});
		}

	};
});
