/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.mycompany.turn.based.game;

/**
 *
 * @author Ellie
 */
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;

public class Player extends JFrame {
    private int width;
    private int height;
    private Container contentPane;
    private JTextArea message; 
    private JButton b1; 
    private JButton b2; 
    private JButton b3; 
    private JButton b4; 
    private int playerID; 
    private int otherPlayer;
    private int[] values;
    private int maxTurns;
    private int turnsMade;
    private int myPoints;
    private int enemyPoints;
    private boolean buttonsEnabled; 
    
    private ClientSideConnection csc;
    
    // setting 
    public Player(int w, int h){
        width = w;
        height = h;
        contentPane = this.getContentPane();
        message = new JTextArea();
        b1 = new JButton("1");
        b2 = new JButton("2");
        b3 = new JButton("3");
        b4 = new JButton("4");
        values = new int[4];
        turnsMade = 0;
        myPoints = 0;
        enemyPoints = 0;
    }
    
   public void setUpGUI(){
       // design interface, layout, text formatting
       this.setSize(width, height);
       this.setTitle("Player #" + playerID); //eg. Player #2
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       contentPane.setLayout(new GridLayout(1, 5));
       contentPane.add(message);
       message.setText("A simple turn-based game in Java.");
       message.setWrapStyleWord(true);
       message.setLineWrap(true);
       message.setEditable(false);
       contentPane.add(b1);
       contentPane.add(b2);
       contentPane.add(b3);
       contentPane.add(b4);
       
       // user feedback, start game, provides turns 
       if (playerID == 1) {
           message.setText("You are player 1, you go first. ");
           otherPlayer = 2;
           buttonsEnabled = true;
       } else {
           message.setText("You are player 2, please wait for your turn.");
           otherPlayer = 1;
           buttonsEnabled = false;  //buttons to show only when turn 
           Thread t = new Thread(new Runnable() {
               public void run() {
                   updateTurn();
               }
           });
           t.start();
       }
       
       toggleButtons();
       
       this.setVisible(true);
   }
   
   public void connectToServer(){
       // start client side connection 
       csc = new ClientSideConnection();
   }
   
   public void setUpButtons() {
       // notifies actions
       ActionListener al = new ActionListener() {
           public void actionPerformed(ActionEvent ae) {
               JButton b = (JButton) ae.getSource();  //get source of what clicked
               int bNum = Integer.parseInt(b.getText()); // access label 
               
               message.setText("You clicked button #" + bNum + ". Wait for player #" + otherPlayer);
               turnsMade++;  //increase after button click 
               System.out.println("Turns Made: " + turnsMade);
               
               // after turn, button disabled
               buttonsEnabled = false;
               toggleButtons();
               
               // track points and add new points
               myPoints += values[bNum - 1];
               System.out.println("My Points: " + myPoints);
               csc.sendButtonNum(bNum); //send btn no 
               
               if (playerID == 2 && turnsMade == maxTurns) { //if 2 turns had, check winner
                   checkWinner();
               } else {
                   Thread t = new Thread(new Runnable() {
                        public void run() {
                            updateTurn();
                        }
                    });
                    t.start();
                }
           } 
       };
       
       b1.addActionListener(al);
       b2.addActionListener(al);
       b3.addActionListener(al);
       b4.addActionListener(al);
   }
   
   public void toggleButtons() {
       //pass true/false
       b1.setEnabled(buttonsEnabled);
       b2.setEnabled(buttonsEnabled);
       b3.setEnabled(buttonsEnabled);
       b4.setEnabled(buttonsEnabled);
   }
   
   public void updateTurn() {
       int n = csc.recieveButtonNum(); //turn updates after button pressed by opponenet is recieved
       message.setText("The enemy chose button #" + n + ". Your turn.");
       enemyPoints += values[n-1];  //current points plus lastest points
       //System.out.println("Your enemy has " + enemyPoints + " points.");
       if (playerID == 1 && turnsMade == maxTurns){  //check for winner after 2 turns
           checkWinner();
       } else {
           buttonsEnabled = true;
       }
       toggleButtons(); 
   }
   
   private void checkWinner(){ 
       //provides 3 only alternatives, then closes connection 
       buttonsEnabled = false;
       if (myPoints > enemyPoints){  //win
           message.setText("You WIN!\n" + "Your Score: " + myPoints + "\n" + "Opponent Score: " + enemyPoints);
       } else if (myPoints < enemyPoints){  // lose
           message.setText("You LOST!\n" + "Your Score: " + myPoints + "\n" + "Opponent Score: " + enemyPoints);
       } else {  // tie 
           message.setText("It's a tie! Both scored " + myPoints + " points.");
       }
       // after win, close connection 
       csc.closeConnection();
   }
   
   // client connection- networking instructions for client
   private class ClientSideConnection{
       
       private Socket socket;
       private DataInputStream dataIn;
       private DataOutputStream dataOut;
       
       public ClientSideConnection(){
           System.out.println("--Client--");
           try {
               socket = new Socket("localhost", 51734);  //same ip, same port-- request to server
               dataIn = new DataInputStream(socket.getInputStream());  //recieve data
               dataOut = new DataOutputStream(socket.getOutputStream());  //send data
               playerID = dataIn.readInt(); // recicves player number
               System.out.println("Connected to server as Player #" + playerID + ".");
               
               maxTurns = dataIn.readInt() / 2;  //2 turns each
               values[0] = dataIn.readInt();
               values[1] = dataIn.readInt();
               values[2] = dataIn.readInt();  //recieve rando number from server
               values[3] = dataIn.readInt(); 
               System.out.println("maxTurns: " + maxTurns);
               System.out.println("Value #1 is  " + values[0]);
               System.out.println("Value #2 is  " + values[1]);
               System.out.println("Value #3 is  " + values[2]);
               System.out.println("Value #4 is  " + values[3]);
           } catch (IOException ex) {
               System.out.println("IO Execption from csc constructor");
           }
       }
       
       public void sendButtonNum( int n) {
           try {
               dataOut.writeInt(n);
               dataOut.flush();
           } catch (IOException ex){
               System.out.println("IOException from sendButtonNum() CSC");
           }
       }
       
       public int recieveButtonNum() {
           int n = -1; 
           try {
               n = dataIn.readInt();  //read int from server
               System.out.println("Player #" + otherPlayer + "clicked button #" + n);
           } catch (IOException ex) {
               System.out.println("IOException from RecieveButtonNum() csc");
           }
           return n;
        }
       
       public void closeConnection() {
           try {
               socket.close();
               System.out.println("--Connection Closed--");
           } catch (IOException ex){
               System.out.println("IOException on closeConnection() csc");
           }
       }
   }
   
   public static void main(String[] agrs){
       // instantiate
       Player p = new Player(500, 100);
       p.connectToServer();
       p.setUpGUI();
       p.setUpButtons();
    }
}
