Skip to content

Instantly share code, notes, and snippets.

@diegoaguilar
Created September 11, 2015 22:11
Show Gist options
  • Save diegoaguilar/cd53febc465057136da8 to your computer and use it in GitHub Desktop.
Save diegoaguilar/cd53febc465057136da8 to your computer and use it in GitHub Desktop.
Angular code
angular.module('mtLigaFantastica')
.controller('LineupViewController', LineupViewController);
function LineupViewController(Restangular, $state, $modal, $window, $log, $interval, $rootScope, $http, $timeout, $localStorage) {
'use strict';
var vm = this;
var _ = $window._; //underscore
var localStorage = $window.localStorage; //localstorage -> hará falta usar ngStorage?
var latency = 2000; // después de este tiempo, se bloquea la interfaz en caso de que no responda el API
/*** FORMACIONES -> clases CSS (elevación de los slots) ***/
vm.lineupClasses = {
1: ['l0'],
2: ['l0', 'l0'],
3: ['l1', 'l0', 'l1'],
4: ['l1', 'l0', 'l0', 'l1'],
5: ['l2', 'l1', 'l0', 'l1', 'l2'],
};
vm.viewport = 'sm'; // tamaño de los modales 'sm', 'lg'
/**** FORMACIONES -> cantidad de slots por posición *** */
// Formaciones -> Orden de las posiciones, de arriba hacia abajo
vm.pos = ['Forward', 'Midfielder', 'Defender', 'Goalkeeper'];
// Formaciones -> Objetos con el límite de slots por posición
vm.formations = [];
function generateFormations() {
var formationTypes = ['3-4-3', '3-5-2', '4-3-3', '4-4-2', '4-5-1', '5-3-2', '5-4-1'];
_.forEach(formationTypes, function(f) {
var split = f.split('-');
var formationObject = {
formation: {},
type: f
};
formationObject.formation['Goalkeeper'] = 1;
formationObject.formation['Defender'] = Number(split[0]);
formationObject.formation['Midfielder'] = Number(split[1]);
formationObject.formation['Forward'] = Number(split[2]);
vm.formations.push(formationObject);
});
}
generateFormations();
// Máximo de slots vacíos en banca
var BENCH_LIMIT = 4;
/**** MODELO ****/
//se usa para controlar qué slots quieren cambiarse {'in', 'out'}
vm.switchList = {};
/**** IDENTIFICADORES ****/
var iduser = localStorage.getItem('iduser'),
lineupId, // string con el id del lineup
baseLineup, // placeholder para el objeto de Restangular que se va a trabajar
uuid;
/**** INIT: OBTENER LOS DATOS DEL LINEUP ****/
// dar formato a los datos para mostrarlos en backend
/**** VALIDACIONES ****/
// validar si el slot está vacío
vm.isEmpty = function(slot) {
return slot === undefined || slot.id === undefined;
};
// validar si el slot está en el campo
vm.isSlotInField = function(slot) {
for (var p in vm.pos) {
p = vm.pos[p];
if (vm.team[p].indexOf(slot) !== -1) {
return true;
}
}
return false;
};
// validar si el slot pertenece a la banca
vm.isSlotInBench = function(slot) {
return _.contains(vm.substitutes, slot);
};
// validar si el slot está en la posición especificada
vm.isSlotInPosition = function(slot, position) {
return vm.team[position].indexOf(slot) !== -1;
};
// obtener la posición de un slot en el campo
vm.getSlotPosition = function(slot) {
if (vm.isSlotInField(slot)) {
for (var p in vm.pos) {
p = vm.pos[p];
if (vm.team[p].indexOf(slot) !== -1) {
return p;
}
}
}
};
// contar slots vacíos en la banca
vm.countEmptySlotsBench = function() {
var count = 0;
_.forEach(vm.substitutes, function(player) {
if (player.id === undefined) {
count++;
}
});
return count;
};
// validar que ambos slots estén el campo y que jueguen en la misma posición
vm.matchPositionField = function(slotIn, slotOut) {
return vm.getSlotPosition(slotIn) === vm.getSlotPosition(slotOut);
};
// validar que ambos slots estén vacíos
vm.matchEmpty = function(slotIn, slotOut) {
return vm.isEmpty(slotIn) && vm.isEmpty(slotOut);
};
// obtener la posición del slot en el campo
vm.getSlotIndexField = function(slot) {
if (vm.isSlotInField(slot)) {
for (var p in vm.pos) {
p = vm.pos[p];
if (vm.team[p].indexOf(slot) !== -1) {
return vm.team[p].indexOf(slot);
}
}
}
};
// validar que ambos slots en la lista de cambios estén definidos
vm.isReadyToSubstitute = function() {
return vm.switchList.in !== undefined && vm.switchList.out !== undefined;
};
vm.isDisabled = function(slot) {
return slot !== undefined && slot.status !== 'normal';
};
vm.isValidLineup = function() {
var substituteCount = 0;
_.forEach(vm.substitutes, function(slot) {
if (!vm.isEmpty(slot)) {
substituteCount++;
}
});
return substituteCount > BENCH_LIMIT;
};
//revisar si la fila position sólo tiene slots vacios
vm.rowIsEmpty = function(position) {
for (var slot in vm.team[position]) {
slot = vm.team[position][slot];
if (!vm.isEmpty(slot)) {
return false;
}
}
return true;
};
/**** MOVIMIENTOS ****/
//agregar el slot a la lista de cambio como in|out
vm.addToSwitchList = function(slot, role) {
if (role === 'in' || role === 'out') {
vm.switchList[role] = slot;
}
};
/**** HANDLERS: GESTIONAR LOS CAMBIOS ****/
/**** MANIPULAR OBJETOS -> estos métodos cambian a team, substitutes y switchList ****/
// desactivar el modo de cambios
vm.clearSwitch = function() {
vm.reorderSubstitutes('std');
vm.switchingMode = false;
vm.selectedRow = false;
vm.switchList = {};
};
/**** FORMATO A DATOS ****/
// actualiza el atributo place de los slots ya que se ocupa en backend
vm.updatePlace = function() {
_.forEach(vm.pos, function(p) {
_.forEach(vm.team[p], function(slot, s) {
if (!vm.isEmpty(slot)) {
vm.team[p][s].place = s;
}
});
});
var substitutesByPosition = _.groupBy(vm.substitutes, 'position');
_.forEach(vm.substitutes, function(s, i) {
if (!vm.isEmpty(s)) {
vm.substitutes[i].place = substitutesByPosition[s.position].indexOf(s);
}
});
};
//wrapper para incluir todas las condiciones en las que es posible
vm.checkValidate = function() {
vm.invalidLineup = vm.isValidLineup();
};
// cambiar formación
vm.changeFormation = function(formation) {
vm.formation = formation;
_.forEach(vm.pos, function(p) {
// comparar cuántos hay con los que se necesitan en esta fila
var current = vm.team[p].length;
var desired = formation['formation'][p];
var diff = Math.abs(desired - current);
var i;
if (current < desired) {
// agregar diff slots
for (i = 0; i < diff; i++) {
vm.team[p].push({});
}
}
if (current > desired) {
// eliminar el slot de más a la derecha
for (i = 0; i < diff; i++) {
var player = vm.team[p][vm.team[p].length - 1];
if (!vm.isEmpty(player)) {
vm.sendToSubstitutes(player);
}
vm.team[p].pop();
}
}
});
vm.updatePlace();
vm.reorderSubstitutes('std');
};
vm.callInSubstitutes = function(position) {
var match = [];
_.forEach(vm.substitutes, function(slot) {
if (slot.position === position) {
match.push(slot);
}
});
return match;
};
vm.reorderSubstitutes = function(style) {
// orden por defecto
var order = ['Goalkeeper', 'Defender', 'Midfielder', 'Forward'];
// esta lista se llenará con los jugadores conforme se vayan seleccionando
var substituteList = [];
if (style !== 'std') {
// eliminar la llave de la lista y ponerla al inicio
order = _.without(order, style);
order.unshift(style);
}
// concatenar las demás posiciones a la lista
_.forEach(order, function(o) {
substituteList = substituteList.concat(vm.callInSubstitutes(o));
});
// completar la banca por si hay menos slots vacíos
var emptySlots = BENCH_LIMIT - substituteList.length;
for (var i = 0; i < emptySlots; i++) {
substituteList.push({});
}
// reemplazar la nueva lista para actualizar la vista
vm.substitutes = substituteList;
};
//devuelve la url de la imagen para que se muestre en cancha.
vm.getImage = function(player,showTeam) {
if(showTeam){
return player.team !== undefined ? "url('http://euro.mediotiempo.com/ligafantastica/fotos/" + player.team.id+ ".jpg')" : '' ;
}else{
return player.id !== undefined ? "url('http://euro.mediotiempo.com/ligafantastica/fotos/" + player.id + ".jpg')" : '';
}
};
// visualizar en cancha la alineación de la jornada seleccionada - la alineación debe bloquearse.
vm.viewLineup = function() {
console.log($state.params.lineupId);
Restangular.one('lineups', $state.params.lineupId).get().then(function(lineup) {
vm.preparePreviousLineup(lineup, 8);
});
};
vm.preparePreviousLineup = function( lineup,round) {
$localStorage[lineup.id] = lineup;
vm.prepareLineup(lineup);
};
vm.prepareLineup = function(data) {
// 1. inicializar equipo y coach como vacíos
vm.team = {
'Goalkeeper': [],
'Defender': [],
'Midfielder': [],
'Forward': []
};
vm.coach = data.coach !== undefined ? [data.coach] : [{}];
//2. agrupar los jugadores en banca o titulares (bench = true/false)
var playerList = _.groupBy(data.players, 'bench');
var startingPlayers = playerList.false;
vm.substitutes = playerList.true !== undefined ? playerList.true : [{}, {}, {}, {}];
vm.reorderSubstitutes('std');
//3. cargar la formación seleccionada
if (data.formation) {
vm.formation = _.findWhere(vm.formations, {
'type': data.formation
});
//llamar a changeFormation para crear los slots de acuerdo a la formación
vm.changeFormation(vm.formation);
}
else {
if (data.matchDate.round === vm.currentRound) {
$state.go('formation', {}, {
reload: true
});
}
// if (vm.lineups[1].formation) {
// vm.formation = _.findWhere(vm.formations, {
// 'type': vm.lineups[1].formation
// });
// //vm.selectFormation(vm.formation);
// }
// else {
// if (vm.lineups[1].formation === undefined && vm.lineups[2].formation === undefined) {
// $state.go('formation', {}, {
// reload: true
// });
// }
// // si no hay formación, hay que solicitarle al usuario que seleccione una alineación
// }
}
var toAdd = [];
//4. llenar la alineacíón a partir de la lista
_.forEach(startingPlayers, function(player) {
player.role = player.captain === 'true' || player.captain === true ? 'C' : undefined;
if (!vm.isEmpty(vm.team[player.position][player.place])) {
$log.error('El jugador', player.id, '(', player.last_name, ')', 'tiene una ubicación incorrecta');
toAdd.push(player);
}
else {
if (player.place >= 0 && player.place < vm.formation['formation'][player.position]) {
vm.team[player.position][player.place] = player;
}
else {
$log.error('El jugador', player.id, '(', player.last_name, ')', 'tiene mal su posición');
}
}
});
_.forEach(toAdd, function(player) {
for (var p in vm.team[player.position]) {
if (vm.isEmpty(vm.team[player.position][p])) {
vm.team[player.position][p] = player;
vm.team[player.position][p].place = p;
vm.changeFormation(vm.formation);
break;
}
}
});
vm.currentLineup = data;
// validar la alineación
vm.invalidLineup = vm.isValidLineup(); //validar que esté en el límite de jugadores en banca
// // obtener la fecha de inicio y restarle 15 minutos
// var startDate = new Date(vm.bundle.lineup.matchDate.startDate);
// startDate.setMinutes(startDate.getMinutes() - 15);
// // construir los objetos Date
// vm.home.lineup.matchDate.startDate = new Date(startDate);
// vm.home.lineup.matchDate.endDate = new Date(vm.home.lineup.matchDate.endDate);
// llamar a $interval para validar si la alineación puede bloquearse
$timeout(function() {
if ($state.current.name === 'team') {
//vm.checkFormationLocked();
}
}, 500);
// vm.myTimeout = $interval(vm.checkFormationLocked, 1000);
};
vm.viewLineup();
/* $rootScope.loadUser(function() {
if ($state.current.name === 'team') {
vm.home = $rootScope.home;
vm.lineups = {}; // ronda: {objeto lineup}
vm.currentRound = $rootScope.getCurrentRound();
vm.viewLineup(vm.currentRound);
//generar dropdown de lineups
vm.availableRounds = _.filter($rootScope.lineUpHistory, function(md) {
return md.round <= vm.currentRound;
}).reverse();
}
});*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment