package jnet.client.gui;

import jnet.client.Client;
import jnet.client.network.NettyClient;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;
import jnet.lib.LogFile;
import jnet.lib.object.Map;
import jnet.lib.object.MapObject;

public class MapView extends JPanel {

    public static List<PaintObject> paintObjects = new ArrayList<>();

    
    private BufferedImage lockImage;
    private BufferedImage unlockImage;

    private static Map map;

    public MapView(Map map) {
        this.map = map;

        LogFile.printDebug("View map: " + map.getName());
        paintObjects.clear();

        try {
            lockImage = ImageIO.read(new File("img/lock.png"));
            unlockImage = ImageIO.read(new File("img/unlock.png"));
        } catch (IOException ex) {
            LogFile.printErr("File not found: " + ex);
        }

        loadObject(map.getId());

        this.addMouseMotionListener(new MapViewAction(map));
        this.addMouseListener(new MapViewAction(map));

        // periodicke prekreslovani
        Timer timer = new Timer(100, (ActionEvent ae) -> {
            if (NettyClient.isConnected()) {
                this.setBackground(Color.white);
            } else {
                this.setBackground(Color.LIGHT_GRAY);
            }
            repaint();
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();

        // vykresleni lock/unlock mapy
        g.drawImage(map.isLock() ? lockImage : unlockImage, 0, 0, this);

        // vykresleni objektu
        for (PaintObject paintObject : paintObjects) {
            paintObject.paint(g2);
        }

    }

    public static void updateMapView(Map map) {
        if (map.equals(MapView.map)) {
            // obnoveni objektu
            paintObjects.clear();
            // nahrat objekty
            loadObject(map.getId());
        }
    }
    
    public static void updateMapView() {
        if (map.equals(MapView.map)) {
            // obnoveni objektu
            paintObjects.clear();
            // nahrat objekty
            loadObject(map.getId());
        }
    }

    private static void loadObject(int mapId) {
        for (Map map : Client.maps) {
            for (MapObject obj : map.getObjects()) {
                if (obj.getMap() == mapId) {
                    paintObjects.add(new PaintObject(obj));
                }
            }
        }

    }

}
