import Node from './Node.js'

export default class Piece extends Node{
	constructor(board, id, containerSvg, x, y, numCol, numRow, unitW, unitH, w, h, isRed, priority) {
		super(board, id, containerSvg, x, y, numCol, numRow, unitW, unitH, w, h)
		this.isRed = isRed;
		this.directEat = true;
		this.priority = priority;
		this.board.cellState[this.x][this.y] = this;
		this.state = "alive";
		this.board.pieceList.push(this);
		//debugger

	}
	draw() {
		if (this.state === "dead"){
			return;
		}
		this.elem = this.svg.append("image")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", this.unitW)
        .attr("height", this.unitH)
        .attr("xlink:href", this.bgImage);
		

	}
	
	remove() {
		this.state = "dead";
		this.elem.style("visibility", function() {return "hidden";})
	}
	
	
	move(x, y, preX, preY) {
		var self = this;
		var preElem = this.board.cellState[x][y];
		self.board.cellState[self.x][self.y] = undefined;
		self.x = x;
		self.y = y;
		self.preX = preX;
		self.preY = preY;
		var duration = Math.abs((Math.sqrt((preX-self.x)*(preX-self.x)+(preY-self.y)*(preY-self.y)))*500)
		
		self.svg.transition().duration(duration).attr("transform", "translate("+self.getX()+", "+self.getY()+")")
		.on('end', function(){
			//debugger
			self.board.cellState[self.x][self.y] = self;
			/*if(preElem.id == "blackKing"){
				alert("Red wins")
	
			}else if(preElem.id == "redKing"){
				alert("Black wins")
	
			}
*/
			
			
			if(preElem !== undefined){
				preElem.state = "dead"
					//preElem.remove();
				 	//this.board.pieceList.splice(preElem);
				 	preElem.elem.style("visibility", function() {return "hidden";})
				 	preElem.remove();
			}
			for(var i = 0; i < self.board.markList.length; i++){
				self.board.markList[i].elem.style("visibility", function() {return "hidden";})

			}
			self.board.markList = [];
			self.board.changeTurns();
		})
		
		
		//this.setSelected();
		
	}
	
	
	findNextSteps() {
		this.setSelected(true);
		var list = [];
/*
		for (var i=0; i<this.markButtonList.length; i++) {
			var b = this.markButtonList[i];
		
			if (this.board.cellState[b.x][b.y]!==undefined) {
				continue;
			}
			list.push(b);
		};
		this.markButtonList = list;

		return list;*/
		return this.markButtonList;
	}
	markTerritory = () => {
		var markedList = this.setSelected(true);
		for (var i=0; i<markedList.length; i++) {
			var button = markedList[i];
			this.board.territoryList[this.isRed][button.x][button.y]++
		}
		
	}
	
}
