
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class Client implements Runnable {
	static Bankacc bank = new Bankacc();
	private int id = 1;

	public static void main(String[] args) throws InterruptedException {
		File myfil = new File("D:\\banklog.txt");
		try {
			FileWriter fw = new FileWriter(myfil);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Client client = new Client();
		Thread one = new Thread(client);
		Thread two = new Thread(client);
		Thread three = new Thread(client);
		Thread four = new Thread(client);
		Thread five = new Thread(client);
		Thread six = new Thread(client);
		Thread seven = new Thread(client);
		Thread eight = new Thread(client);

		one.setName("Андрей");
		two.setName("Борис");
		three.setName("Валентин");
		four.setName("Галя");
		five.setName("Денис");
		six.setName("Егор");
		seven.setName("Игорь");
		eight.setName("Екатерина");

		one.start();
		two.start();
		three.start();
		four.start();
	    five.start();
		six.start();
		seven.start();
		eight.start();
		two.join();
		three.join();
		four.join();
		five.join();
		six.join();
		seven.join();
		eight.join(); 
	}

	public void run() {		
		Random r = new Random();
		
		for (int i = 0; i < 20; i++) {
		    try {
				Thread.sleep(250);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			int fate = r.nextInt(4);
			int currsumm = r.nextInt(100) + 50;
			if (fate == 1) {
				bank.putOn(currsumm);
				String s = getId() + " " + Thread.currentThread().getName() + " Положил на счёт " + currsumm + " Cейчас на счёту: " + bank.getBalance();
				System.out.println(s);				
				idPlus();
			} else {
				if (bank.getBalance() <= 0) {
					String s = getId() + " " + "Извини " + Thread.currentThread().getName() + " но деньги закончились";
					System.out.println(s);
					try {
						Write.log(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
					Thread.currentThread().interrupt();
					idPlus();
					i = 20;
				}
				if (bank.getBalance() < currsumm) {
					int temp = bank.getBalance();
					bank.withdraw(bank.getBalance());
					String s = getId() + " " + Thread.currentThread().getName() + " Хотел снять со счёта " + currsumm + " .Но на счету осталось лишь " + temp + " Cейчас на счёту: " + bank.getBalance();
					System.out.println(s);
					try {
						Write.log(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
					idPlus();
					i = 20;
				} else {
					bank.withdraw(currsumm);
					String s = getId() + " " + Thread.currentThread().getName() + " Снял со счёта " + currsumm + " Cейчас на счёту: " + bank.getBalance();
					System.out.println(s);
					try {
						Write.log(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
					idPlus();
				}
			}
		}
		Thread.yield();
	}

	public synchronized int idPlus() {
	   return  id++;
	}
	public  synchronized int getId() {
		return id;
	}
}
