package lab00;

import java.awt.Color;

import javax.swing.Timer;

public class Line {
	Square[] mem;
	int num;
	TicTacToe game;
	boolean blinker;

	/**
	 * 
	 */
	public Line(TicTacToe game) {
		this.game=game;
		mem=new Square[3];
		num=0;
	}
	
	public void add(Square ns) {
		mem[num]=ns;
		num++;
	}
	
	public boolean isWinner() {
		int i;
		String v;
		v=mem[0].getText();
		if (v.equals(" ")) { return false; }
		for (i=1;i<num;i++) {
			if (!mem[i].getText().equals(v)) return false;
		}
		game.disableAllSquares();
		for(i=0;i<num;i++) mem[i].setOpaque(true);
		blinker=false;
		Timer blinkTimer = new Timer(300, e->{
			for(int j=0;j<num;j++)  mem[j].setBackground( blinker ? Color.GREEN : null);
			blinker=!blinker;
		});
		blinkTimer.start();
		return true;
	}
	
	Square allButOne(String check) {
		int cnt=0;
		Square res=null;
		for(int i=0;i<num;i++) {
			if (mem[i].getText().equals(check)) cnt++;
			else if (!mem[i].getText().equals(" ")) return null;
			else res=mem[i];
		}
		if (cnt!=2) return null;
		return res;
	}
	
	Square avail() {
		for (int i=0;i<num;i++) {
			if (mem[i].getText().equals(" ")) return mem[i];
		}
		return null;
	}
	
	Square getSquare(int i) {
		return mem[i];
	}
	
	void disableAllSquares() {
		for (int i=0;i<num;i++) {
			mem[i].setEnabled(false);
		}
	}
	
	Square getFork(Line other,String val) {
		// Is there a common unchosen square between this and other
		//    that is unchosen and will make two possible winners
		Square common = common(other);
		if (common==null) return null;
		if (!common.getText().equals(" ")) return null;
		// Both lines must contain a single val value
		if (!canFork(val)) return null;
		if (!other.canFork(val)) return null;
		return common;
	}
	
	public boolean onlyOne(String val) {
		boolean found=false;
		for(Square sq : mem) {
			if (sq.getText().equals(val)) {
				if (found) return false;
				found=true;
			}
			else if (!sq.getText().equals(" ")) return false;
		}
		return found;
	}

	private Square common(Line other) {
		// returns the square shared by the two lines or null
		Square common=null;
		for(Square sq: mem) {
			for (Square osq: other.mem) {
				if (sq==osq) return sq;
				
			}
		}
		return null;
	}
	
	private boolean canFork(String val) {
		boolean foundVal=false;
		for(Square sq : mem) {
			if (!sq.getText().equals(val)) {
				if (!sq.getText().equals(" ")) return false;
			} else {
				foundVal=true;
			}
		}
		return foundVal;
	}
}
