<?php include("top.php"); ?>
<div id="regionInfo">
</div>
<script src="snap/dist/snap.js"></script>
<div id="paper">
    <svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" style="background: #96acdc"><desc></desc><defs></defs>
    </svg>
</div>
<script>
var windowShare = 1;
var popupShareX = 0.5;
var popupShareY = 0.4;
var popupOffsetX = 0.25;
var popupOffsetY = 0.2;

var hexaWidth = 400;
var hexaHeight = 353;
var buildingShareX = 0.6;
var buildingShareY = 0.6;

var scaleFactor = 1.05;
var movingZone = 0.1;
var moveSpeed = 20;
var zoomSpeed = 1.1;

var fluxWidth = 120;
var fluxHeight = 40;
var fluxSpeed = 1;

var paperWidth = window.innerWidth * windowShare;
var paperHeight = window.innerHeight * windowShare;


var s = Snap("#svg");

var paper = document.getElementById("svg");
if (paper.addEventListener) {
	paper.addEventListener("mousewheel", mouseWheelHandler, false);
	paper.addEventListener("DOMMouseScroll", mouseWheelHandler, false);
}
else {
	paper.attachEvent("onmousewheel", mouseWheelHandler);
}
paper.setAttribute("width", paperWidth + 'px');
paper.setAttribute("height", (paperHeight-70) + 'px');
var svgX = paper.getBoundingClientRect().left;
var svgY = paper.getBoundingClientRect().top;

var group = s.g();
s.append(group);
group.drag();

window.requestAnimationFrame(draw);

//------------------------------------------------------------------------
//Hexa
//------------------------------------------------------------------------

var hexas = [];
<?

for ($i = -1; $i <= 1; $i++) {
    for ($j = -1; $j <= 1; $j++) {
        $regionId = getRegionId(getRegionX($_SESSION['regionId']) + $i, getRegionY($_SESSION['regionId']) + $j);
        
        $req = $bdd->prepare('SELECT * FROM cTerritories WHERE id >= ? AND id <= ?');
        $req->execute(array(getMinTerritoryId($regionId), getMaxTerritoryId($regionId)));
        while ($data = $req->fetch()) {
            $isBorder = false;
            $isGrayed = true;
            $x = getTerritoryXInRegion($data['id'], $regionId);
            $y = getTerritoryYInRegion($data['id'], $regionId);
            
            if ($i == -1 && $j == -1 && $x == getRegionWidth() - 1 && $y == getRegionHeight() - 1) {
                $isBorder = true;
            }
            else if ($i == -1 && $j == 0 && $x == getRegionWidth() - 1){
                $isBorder = true;
            }
            else if ($i == -1 && $j == 1){
                //none
            }
            else if ($i == 0 && $j == -1 && $y == getRegionHeight() - 1){
                $isBorder = true;
            }
            else if ($i == 0 && $j == 0){
                $isBorder = true;
                $isGrayed = false;
            }
            else if ($i == 0 && $j == 1 && $y == 0){
                $isBorder = true;
            }
            else if ($i == 1 && $j == -1){
                //none
            }
            else if ($i == 1 && $j == 0 && $x == 0){
                $isBorder = true;
            }
            else if ($i == 1 && $j == 1 && $x == 0 && $y == 0){
                $isBorder = true;
            }
            
            if ($isBorder) {
                ?>
                var x = <? echo $x + $i * getRegionWidth();?>;
                var y = <? echo $y + $j * getRegionHeight();?>;
                var color = <? echo getTerrainColor($data['type'], true);?>;
                var interactable = <? if (!$isGrayed) echo "true"; else echo "false";?>;
                
                if (x == 4 && y == 5) {
                    addHexa(x, y, color, 1, interactable);
                    //console.log(hexas.length);
                }
                else if (x == 5 && y == 5) {
                    addHexa(x, y, color, 2, interactable);
                }
                else if (x == 6 && y == 5) {
                    addHexa(x, y, color, 3, interactable);
                }
                else if (x == 5 && y == 4) {
                    console.log(hexas.length);
                    addHexa(x, y, color, 4, interactable);
                }
                else if (x == 4 && y == 4) {
                    addHexa(x, y, color, 5, interactable);
                }
                else {
                    addHexa(x, y, color, 0, interactable);
                }
                
                <?
            }
        }
    }
}


?>

function addHexa(x, y, color, buildingType, interactable) {
    var scaleX = hexaWidth / 400;
    var scaleY = hexaHeight / 353;
    
    var offsetX = hexaWidth * 0.75 * x;
    var offsetY = hexaHeight * y;
    
    if (Math.abs(x) % 2 == 1) {
        offsetY += hexaHeight / 2;
    }
    
    var pol = s.polygon(99 * scaleX + offsetX, 0 * scaleY + offsetY, 299 * scaleX + offsetX, 0 * scaleY + offsetY, 399 * scaleX + offsetX, 176 * scaleY + offsetY, 299 * scaleX + offsetX, 353 * scaleY + offsetY, 99 * scaleX + offsetX, 353 * scaleY + offsetY, 0 * scaleX + offsetX, 176 * scaleY + offsetY);
    pol.attr({ stroke: 'white', 'strokeWidth': "2px", fill: color});
    pol.isBeingHovered = false;
    pol.currentScale = 1;
    pol.centerX = offsetX + hexaWidth/2;
    pol.centerY = offsetY + hexaHeight/2;
    pol.buildingType = buildingType;
    pol.building = 0;
    
    pol.fluxes = [];
    
    pol.group = s.g();
    pol.group.append(pol);
    
    if (!interactable) {
        pol.attr({"pointerEvents": "none"});
        //var stripe = s.polygon(82 * scaleX + offsetX, 324 * scaleY + offsetY, 99 * scaleX + offsetX, 353 * scaleY + offsetY, 134 * scaleX + offsetX, 353 * scaleY + offsetY, 318 * scaleX + offsetX, 30 * scaleY + offsetY, 299 * scaleX + offsetX, 0 * scaleY + offsetY, 264 * scaleX + offsetX, 0 * scaleY + offsetY);
        var stripe = s.polygon(38 * scaleX + offsetX, 238 * scaleY + offsetY, 63 * scaleX + offsetX, 281 * scaleY + offsetY, 363 * scaleX + offsetX, 107 * scaleY + offsetY, 338 * scaleX + offsetX, 65 * scaleY + offsetY);

        stripe.attr({fill: "#b3c7cb"});
        pol.group.append(stripe);
    }
    
    group.append(pol.group);
    hexas.push(pol);
    
    
    pol.hover(function(){
        pol.isBeingHovered = true;
        setInfo("<p> Poli </p>");
    }, function() {
        pol.isBeingHovered = false;
        removeInfo();
    });
    
    pol.click(function(){
    });
}

//------------------------------------------------------------------------
//Buildings
//------------------------------------------------------------------------

<?
$buildings = getBuildingsList();

for ($i = 0; $i < count($buildings); $i++) {
    ?>
    var cou = Snap.load("resources/buildings/<? echo $buildings[$i];?>.svg", function (f) {
        var smallGroup = s.g();
        smallGroup.append(f);
        
        smallGroup.attr({"pointerEvents": "none"});
        
        var width = smallGroup.getBBox().w;
        var height = smallGroup.getBBox().h;
        
        var scaleX = hexaWidth * buildingShareX / width;
        var scaleY = hexaHeight * buildingShareY / height;
        var scale = Math.min(scaleX, scaleY);
        
        var t = new Snap.Matrix();
        t.scale(scale);
        smallGroup.transform(t);
        
        for (var i = 0; i < hexas.length; i++) {
            if (hexas[i].buildingType == <? echo $i+1;?>) {
                var g = smallGroup.clone();
                hexas[i].building = g;
                
                var t = new Snap.Matrix();
                t.translate(hexas[i].centerX - (scale * width) / 2, hexas[i].centerY - (scale * height) / 2);
                t.add(g.transform().localMatrix);
                g.transform(t);
                
                hexas[i].group.append(g);
            }
        }
        
        smallGroup.remove();
    });
    <?
}

?>

//------------------------------------------------------------------------
//Building interaction
//------------------------------------------------------------------------

fluxes = [];
//createFlux(66, 76, "#17c31f");
//createFlux(66, 65, "#c31717");
//createFlux(75, 66, "#17c31f");
//createFlux(76, 86, "#17c31f");

function createFlux(indexHexa1, indexHexa2, color) {
    
    var px1 = hexas[indexHexa1].centerX;  //points coordinates
    var px2 = hexas[indexHexa2].centerX;
    var py1 = hexas[indexHexa1].centerY;
    var py2 = hexas[indexHexa2].centerY;
    
    var x = px1 - fluxWidth / 2;
    var y = py1 - fluxHeight / 2;
    
    var g = group.g();
    
    g.arrows = [];
    
    for (var i = 0; i < 4; i++) {
        var arrow = addArrow(x + 30 * i, y, g);
        
        arrow.attr({fill: color});
        arrow.x = 30 * i;
        g.arrows.push(arrow);
    }
    
    var rect = g.rect(x, y, fluxWidth, fluxHeight);
    g.baseRect = rect;
    rect.attr({"fill-opacity": 0});
    
    var angle = 180 + Snap.angle(px1, py1, px2, py2);
    
    var t = new Snap.Matrix();
    t.rotate(angle, x + fluxWidth / 2, y + fluxHeight / 2);
    t.translate(hexaHeight / 2, 0);
    t.add(g.transform().localMatrix);
    g.transform(t);
    
    g.isBeingHovered = false;
    g.currentScale = 1;
    g.centerX = px1 + Math.cos(Snap.rad(angle)) * hexaHeight / 2;
    g.centerY = py1 + Math.sin(Snap.rad(angle)) * hexaHeight / 2;
    g.hover(function(){
        g.isBeingHovered = true;
        setInfo("<p> Flux </p>")
    }, function() {
        g.isBeingHovered = false;
        removeInfo();
    });
    
    fluxes.push(g);
    
    hexas[indexHexa1].fluxes.push(g);
    
    hexas[indexHexa2].fluxes.push(g);
    group.append(g);
    //hexas[indexHexa2].group.append(g);
    //group.append(hexas[indexHexa2].group);
    return g;
}

function addArrow(x, y, g) {
    var points = [0, 0, 10, 0, 30, fluxHeight / 2, 10, fluxHeight, 0, fluxHeight, 20, fluxHeight / 2];
    
    for (var i = 0; i < points.length; i++) {
        if (i % 2 == 0) {
            points[i] += x;
        }
        else {
            points[i] += y;
        }
    }
    var arrow = g.polygon(points);
    return arrow;
}

function arrowAlpha(x) {
    if (x < 0) {
        return (-20 - x) / (-20);
    }
    else if (x > fluxWidth - 40) {
        return (fluxWidth - 20 - x) / (20);
    }
    return 1;
}
//------------------------------------------------------------------------
//Interface
//------------------------------------------------------------------------

function setInfo(txt) {
    document.getElementById("regionInfo").innerHTML = txt;
    document.getElementById("regionInfo").style.display = "initial";
}

function removeInfo() {
    document.getElementById("regionInfo").style.display = "none";
}

//------------------------------------------------------------------------
//Draw
//------------------------------------------------------------------------

function draw() {
    window.requestAnimationFrame(draw);
    //Hexas
    for (var i = 0; i < hexas.length; i++) {
        if (hexas[i].isBeingHovered && hexas[i].currentScale < 1.3) {
            for (var j = 0; j < hexas[i].fluxes.length; j++) {
                hexas[i].group.append(hexas[i].fluxes[j]);
            }
            group.append(hexas[i].group);
            
            hexas[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, hexas[i].centerX, hexas[i].centerY);
            t.add(hexas[i].group.transform().localMatrix);
            hexas[i].group.transform(t);
            
            hexas[i].attr({'strokeWidth': (4 * hexas[i].currentScale) + "px"});
        }
        else if (!hexas[i].isBeingHovered && hexas[i].currentScale > 1){
            hexas[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, hexas[i].centerX, hexas[i].centerY);
            t.add(hexas[i].group.transform().localMatrix);
            hexas[i].group.transform(t);
            
            hexas[i].attr({'strokeWidth': (2 * hexas[i].currentScale) + "px"});
        }
    }
    
    //Fluxes hover
    for (var i = 0; i < fluxes.length; i++) {
        if (fluxes[i].isBeingHovered && fluxes[i].currentScale < 2) {
            
            fluxes[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, fluxes[i].centerX, fluxes[i].centerY);
            t.add(fluxes[i].transform().localMatrix);
            fluxes[i].transform(t);
        }
        else if (!fluxes[i].isBeingHovered && fluxes[i].currentScale > 1){
            fluxes[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, fluxes[i].centerX, fluxes[i].centerY);
            t.add(fluxes[i].transform().localMatrix);
            fluxes[i].transform(t);
        }
    }
    
    //Fluxes arrows
    for (var i = 0; i < fluxes.length; i++) {
        for (var j = 0; j < fluxes[i].arrows.length; j++) {
            fluxes[i].arrows[j].x += fluxSpeed;
            
            if (fluxes[i].arrows[j].x > fluxWidth - 20) {
                fluxes[i].arrows[j].x = - 20;
                var t = new Snap.Matrix();
                t.translate(-fluxWidth, 0);
                t.add(fluxes[i].arrows[j].transform().localMatrix);
                fluxes[i].arrows[j].transform(t);
            }
            else {
                var t = new Snap.Matrix();
                t.translate(fluxSpeed, 0);
                t.add(fluxes[i].arrows[j].transform().localMatrix);
                fluxes[i].arrows[j].transform(t);
            }
            fluxes[i].arrows[j].attr({"fill-opacity": arrowAlpha(fluxes[i].arrows[j].x)});
            
        }
    }
    
    if (left.isDown || ak.isDown){
        left.press();
    }
    
    if (right.isDown || dk.isDown){
        right.press();
    }
    
    if (up.isDown || wk.isDown){
        up.press();
    }
    
    if (down.isDown || sk.isDown){
        down.press();
    }
}

function moveGroup(x, y) {
    t = new Snap.Matrix();
    t.translate(x * moveSpeed, y * moveSpeed);
    t.add(group.transform().localMatrix);
    group.transform(t);
}

//------------------------------------------------------------------------
//Mouse
//------------------------------------------------------------------------

var mousePos;

document.getElementById("svg").onmousemove = (function(event) {
    mousePos = {
        x: event.offsetX,
        y: event.offsetY
    };
});

//------------------------------------------------------------------------
//Keyboard
//------------------------------------------------------------------------

var left = keyboard(37);
var ak = keyboard(65);

ak.press = left.press = function() {
    moveGroup(1, 0);
};

var right = keyboard(39);
var dk = keyboard(68);

dk.press = right.press = function() {
    moveGroup(-1, 0);
};

var up = keyboard(38);
var wk = keyboard(87);

wk.press = up.press = function() {
    moveGroup(0, 1);
};

var down = keyboard(40);
var sk = keyboard(83);

sk.press = down.press = function() {
    moveGroup(0, -1);
};


function keyboard(keyCode) {
  var key = {};
  key.code = keyCode;
  key.isDown = false;
  key.isUp = true;
  key.press = undefined;
  key.release = undefined;
  //The `downHandler`
  key.downHandler = function(event) {
    if (event.keyCode === key.code) {
      key.isDown = true;
      key.isUp = false;
    }
    event.preventDefault();
  };

  //The `upHandler`
  key.upHandler = function(event) {
    if (event.keyCode === key.code) {
      key.isDown = false;
      key.isUp = true;
    }
    event.preventDefault();
  };

  //Attach event listeners
  window.addEventListener(
    "keydown", key.downHandler.bind(key), false
  );
  window.addEventListener(
    "keyup", key.upHandler.bind(key), false
  );
  return key;
}

//------------------------------------------------------------------------
//Wheel
//------------------------------------------------------------------------

function mouseWheelHandler(event) {
	var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
	
	if ((event.wheelDelta || -event.detail) > 0) {
        var t = new Snap.Matrix();
        t.scale(zoomSpeed, zoomSpeed, event.pageX-svgX, event.pageY-svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
	else {
		var t = new Snap.Matrix();
        t.scale(1/zoomSpeed, 1/zoomSpeed, event.pageX-svgX, event.pageY-svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
}
</script>
<?php include("bottom.php"); ?>