## a PCT economics model, version 0.01
## 
##


class ControlLoop
 	def initialize (aGain,aRef,adt)
		@gain = aGain
		@ref = aRef
		@dt = adt
	end
	def Step (qi)
		perc = qi
		err = @ref - perc
		qo=@gain*err*@dt
		return qo
	end
end

require 'tk'  

# starting variables
a_goodx = 0.00
s_goodx = 100.00
a_money = 50.00
s_money = 50.00

price = 1.00

rg = 30
a_gain = 600
dt = 0.001
cs = ControlLoop.new(a_gain,rg,dt)



main = TkRoot.new {
	title "Testing"
	minsize(300,300)
}

act1 = TkFrame.new(main) {
	pack('side'=>'left', 'padx' => 10);
}
shop1 = TkFrame.new(main) {
	pack('side'=>'right', 'padx'=>30);
} 
label0 = TkLabel.new(act1) { text "- Actor1 -"; pack('pady'=> 15) } 
lblGood = TkLabel.new(act1) { text "Good X: #{a_goodx.to_s}";  pack; }
lblRg = TkLabel.new(act1) { text "Rg: #{rg.to_s}"; pack }
lblMoney = TkLabel.new(act1) { text "Money: #{a_money.to_s}"; pack  }
btnTake = TkButton.new(act1) {
	text 'Take 1';
	command  {a_goodx=a_goodx-1}; 
	pack 
	}
	
btnGive = TkButton.new(act1) { 
	text 'Give 1';
	command  {a_goodx=a_goodx+1}; 
	pack('pady'=>10) }     
	
slabel0 = TkLabel.new(shop1) { text '- Shop1 -'; pack('side' =>'top') } 
slblGood = TkLabel.new(shop1) { text "Good X: #{s_goodx.to_s}"; pack  }
slblMoney = TkLabel.new(shop1) { text "Money: #{s_money.to_s}"; pack  }


btnStart = TkButton.new(main) do
	text 'START';
	command{
		$running = 1 
		Thread.new{
		
		while ($running==1)do
			if(a_money > 0) then 
				step = cs.Step(a_goodx).round(2);
			
				a_goodx = (a_goodx + step).round(2);
				s_goodx = (s_goodx - step).round(2);
				cost = (price*step).round(2);
				a_money = (a_money - cost).round(2);
				s_money = (s_money + cost).round(2);
			
				lblGood.text = "GoodX:  #{a_goodx.to_s}";
				lblMoney.text = "Money:  #{a_money.to_s}";
				slblGood.text = "GoodX:  #{s_goodx.to_s}";
				slblMoney.text = "Money:  #{s_money.to_s}";
			
				sleep (0.1);	
				
			 else 
				Tk.messageBox( 	'type'    => "ok",  
								'icon'    => "info", 
								'title'   => "Trading over",
								'message' => "No more money"
							)
				$running = 0
				
			end
		end
		} 
		}
		pack;
end

btnStop = TkButton.new(main) do
	text 'STOP'
	command { $running = 0 }
	pack;
end

Tk.mainloop
