import javax.swing.*;
import java.awt.*; 
import java.awt.Graphics;

public class Tank extends JPanel
{
    private JFrame frame;
    public int frameHeight, frameWidth;
    private int x = 0, y, width = 30, height = 10, step = 3;
    private int muzzleAngle = 270, muzzleStep = 5, muzzleLength = 15;
    private int muzzleX, muzzleY;
    private double speed = 0, muzzleSpeed = 0;
    private double[] sin, cos;
        
    public Tank(JFrame frame)
    {
        this.frame = frame;
        this.frameHeight = (int)(this.frame.getHeight());
        this.frameWidth = (int)(this.frame.getWidth());
        
        this.y = this.frameHeight - this.height - 23;
        
        this.sin = new double[361];
        this.cos = new double[361];
        
        for(int i = 0; i <= 360; i++)
        {
            double rad = Math.toRadians(i);
            this.sin[i] = Math.sin(rad);
            this.cos[i] = Math.cos(rad);
        }
        computeMove();
        repaint();     
    }
    
    public void paintComponent(Graphics g)
    {        
        super.paintComponent(g);
        
        g.drawRect(
            this.x,
            this.y,
            this.width,
            this.height
        );
        
        int muzzleX = this.x + (int)(width*0.5);
        g.drawLine(
            muzzleX,
            this.y,
            muzzleX + this.muzzleX,
            this.y + this.muzzleY
        );        
    }
    
    public void move()
    {
        if(Math.abs(this.speed) > 0.1 || Math.abs(this.muzzleSpeed) > 0.1)
        {
            computeMove();
            repaint();
        }
    }
    
    private void computeMove()
    {
        this.speed *= 0.9;
        this.x += this.speed;
        
        this.muzzleSpeed *= 0.9;
        
        int nowAngle = this.muzzleAngle - (int)this.muzzleSpeed;

        this.muzzleX = (int)(SinCosLookup.getCos(nowAngle) * this.muzzleLength);
        this.muzzleY = (int)(SinCosLookup.getSin(nowAngle) * this.muzzleLength);
    }
    
    public void goRight()
    {        
        if(this.x < this.frameWidth - this.width)
            this.speed = this.step;
    }
    
    public void goLeft()
    {
        if(this.x > 0)
            this.speed = - this.step;
    }
    
    public void muzzleLeft()
    {
        if(this.muzzleAngle > 200)
        {
            this.muzzleSpeed -= this.muzzleStep;
            this.muzzleAngle -= this.muzzleStep;
        }
    }
    
    public void muzzleRight()
    {
        if(this.muzzleAngle < 340)
        {
            this.muzzleSpeed += this.muzzleStep;
            this.muzzleAngle += this.muzzleStep;
        }
    }
    
    public void fire()
    {        
        Bullet bullet = new Bullet(
            this.muzzleAngle,
            this.x + (int)(width*0.5) + this.muzzleX,
            this.y + this.muzzleY,
            this.speed,
            0
        );
                
        BulletPool.add(bullet);
        
        this.frame.getContentPane().add(bullet);
    }
}