package kamiworldserver.elem;

import java.io.IOException;
import java.net.MalformedURLException;
import kamiworldserver.KamiServer;
import java.net.URL;
import java.net.URLConnection;

public class KamiLink {

    //<link id="1" x="12" y="6" width="6" height="1" type="normal" map="w/world/default.map" nx="20" ny="30"/>
    public int x;
    public int y;
    public int w;
    public int h;
    public String map;
    public short nx;
    public short ny;
    public short vx;
    public short vy;
    public URL url;

    public KamiLink(int _x, int _y, int _w, int _h, String _map, short _nx, short _ny) {
        x = _x;
        y = _y;
        w = _w;
        h = _h;
        map = _map;
        nx = _nx;
        ny = _ny;
        try {
            url = new URL("http://" + KamiServer.sHost + "/" + map.replaceAll(" ", "%20"));
        } catch (MalformedURLException ex) {
            System.out.println("Error in URL. Message: "+ex);
        }
    }

    public KamiLink(int _x, int _y, int _w, int _h, String _map, String sx, String sy) {
        x = _x;
        y = _y;
        w = _w;
        h = _h;
        map = _map;

        int i;
        if ((i = sx.indexOf('x')) != -1) {
            if (i > 0 && sx.charAt(i - 1) == '-') {
                vx = -1;
            }
            vx = 1;
        }
        String[] s = sx.split("(-x|-y|x|y|\\+x|\\+y)[^\\-\\d]?");
        if (s[0].length() > 0) {
            nx = Short.parseShort(s[0]);
        } else {
            nx = Short.parseShort(s[1]);
        }

        if ((i = sy.indexOf('y')) != -1) {
            if (i > 0 && sy.charAt(i - 1) == '-') {
                vy = -1;
            } else {
                vy = 1;
            }
        }
        s = sy.split("(-x|-y|x|y|\\+x|\\+y)[^\\-\\d]?");
        if (s[0].length() > 0) {
            ny = Short.parseShort(s[0]);
        } else {
            ny = Short.parseShort(s[1]);
        }

        try {
            url = new URL("http://" + KamiServer.sHost + "/" + map.replaceAll(" ", "%20"));
        } catch (MalformedURLException ex) {
            System.out.println("Error in URL. Message: "+ex);
        }

    //nx  = _nx;
    //ny  = _ny;
    }

    public short getNX(short x) {
        return (short) (nx + (vx * x));
    }

    public short getNY(short y) {
        return (short) (ny + (vy * y));
    }

    public boolean notInLink(short px, short py) {
        return px < x || px > x + w || py < y || py > py + h;
    }

    public boolean validLink() {
        try {
            URLConnection con = url.openConnection();
            String cont = con.getContentType();
            int l = con.getContentLength();
            return (l > 0) && cont.equals("text/plain");
        } catch (IOException ex) {
            System.out.println("Error with URL validation. Message: "+ex);
            return false;
        }
    }
}
