package cicaprojekt;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JPanel;

public class Display extends JPanel{
    private List<Drawer> visuals;
    private Clip clip;

    public Display() {
        visuals = new ArrayList<>();
        setVisible(false);
    }
    
    public void addVisual(Drawer visual) {
        visuals.add(visual);
    }
    
    public void drawVisuals() throws IOException {
        for(Drawer visual : visuals)
            visual.draw();
        repaint();
        setVisible(true);
    }

    public void startMusic() {
        try(AudioInputStream ais =
                    AudioSystem.getAudioInputStream(new File("tomboy2.wav"))) {
            clip = AudioSystem.getClip();
            clip.open(ais);
            clip.start();
        }
        catch(Exception e) {
            e.printStackTrace(System.out);
        }
    }

    public void stopMusic() {
        clip.stop();
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for(Drawer visual : visuals)
            g.drawImage(visual.getImage(), visual.getTileX() * 64, visual.getTileY() * 64, null);
    }

    public void gapMagic(Gap gap, Field field, int mapwidth) {
        try {
            visuals.set((gap.getY()*mapwidth)+gap.getX(), new FieldDrawer(field));
        }
        catch (IOException e) {
            Control.ioErrorMessage();
        }
    }

    public void setMapSize(int width, int height) {
        Dimension dimension = new Dimension(width * 64, height * 64);
        setPreferredSize(dimension);
        setMinimumSize(dimension);
    }
}