<?
//------------------------------------------------------------------------
//Ut
//------------------------------------------------------------------------

function nullIsZero($data) {
    return nullIs($data, 0);
}

function nullIs($data, $replace) {
    if (is_null($data)) {
        return $replace;
    }
    else {
        return $data;
    }
}

function prodPerSec($valPerHour) {
    return $valPerHour / 3600;
}

function prodPerHour($valPerSec) {
    return $valPerSec * 3600;
}

function addPlus($num) {
    if ($num >= 0) {
        return "+" . $num;
    }
    return $num;
}

function timeToString($time, $delim) {
	$str = "";
	if ($time >= 7200) {
		$str = (int) ($time / 3600) . " hours";
		$time = $time % 3600;
	}
	else if ($time >= 3600) {
		$str = (int) ($time / 3600) . " hour";
		$time = $time % 3600;
	}
	
	if ($time >= 120) {
		if ($str != "") {
			$str = $str . $delim;
		}
		$str = $str . (int) ($time / 60) . " minutes";
		$time = $time % 60;
	}
	else if ($time >= 60) {
		if ($str != "") {
			$str = $str . $delim;
		}
		$str = $str . (int) ($time / 60) . " minute";
		$time = $time % 60;
	}
	
	if ($time >= 2) {
		if ($str != "") {
			$str = $str . $delim;
		}
		$str = $str . (int) ($time) . " seconds";
	}
	else if ($time >= 1) {
		if ($str != "") {
			$str = $str . $delim;
		}
		$str = $str . (int) ($time) . " second";
	}
	return $str;
}

//------------------------------------------------------------------------
//Map
//------------------------------------------------------------------------

function getMapWidth() { //in territory
    return 100;
}

function getMapHeight() { //in territory
    return 96;
}

function getRegionWidth() { //in territory
    return 10;
}

function getRegionHeight() { //in territory
    return 8;
}

function getHexaWidth() { //in svg units
    return 10;
}

function getHexaHeight() { //in svg units
    return 8.660025;
}

function getTerritoryXInRegion($id, $regionId) {
    return intval(($id-getMinTerritoryId($regionId)) / getRegionHeight());
}

function getTerritoryYInRegion($id, $regionId) {
    return intval(($id-getMinTerritoryId($regionId)) % getRegionHeight());
}

function getTerritoryX($id) {
    $region = getRegionFromTerritory($id);
    return getTerritoryXInRegion($id, $region) + getRegionX($region) * getRegionWidth();
}

function getTerritoryY($id) {
    $region = getRegionFromTerritory($id);
    return getTerritoryYInRegion($id, $region) + getRegionY($region) * getRegionHeight();
}

function getTerritoryId($x, $y) {
    $region = getRegionId(intval($x / getRegionWidth()), intval($y / getRegionHeight()));
    return getMinTerritoryId($region) + ($x % getRegionWidth()) * getRegionHeight() + ($y % getRegionHeight());
}

function getRegionFromTerritory($id) {
    return 1 + intval(($id-1) / (getRegionWidth() * getRegionHeight()));
}

function getRegionX($id) {
    return intval(($id-1) / (getMapHeight() / getRegionHeight()));
}

function getRegionY($id) {
    return ($id-1) % (getMapHeight() / getRegionHeight());
}

function getRegionId($x, $y) {
    return 1 + $x * (getMapHeight() / getRegionHeight()) + $y;
}

function getMinTerritoryId($regionId) {
    return intval(($regionId-1) * getRegionWidth() * getRegionHeight() + 1);
}

function getMaxTerritoryId($regionId) {
    return intval(($regionId) * getRegionWidth() * getRegionHeight());
}

function getNeighbourgs($id) {
    $x = getTerritoryX($id);
    $y = getTerritoryY($id);
    $a = [];
    
    for ($i = -1; $i <= 1; $i++) {
        for ($j = -1; $j <= 1; $j++) {
            
            if ($i == 0 && $j == 0) {
                //do not add
            }
            else if ($x % 2 == 0) {
                if (abs($i) == 1 && $j == 1) {
                    //do not add
                }
                else {
                    $a[] = getTerritoryId($x + $i, $y + $j);
                }
            }
            else if ($x % 2 == 1) {
                if (abs($i) == 1 && $j == -1) {
                    //do not add
                }
                else {
                    $a[] = getTerritoryId($x + $i, $y + $j);
                }
            }
        }
    }
    
    return $a;
}

//------------------------------------------------------------------------
//Colors
//------------------------------------------------------------------------

function getFluxColor($val) {
    if ($val >= 0) {
        return "'#17c31f'";
    }
    else {
        return "'#c31717'";
    }
}

//------------------------------------------------------------------------
//Terrain
//------------------------------------------------------------------------

function getTerrainsList() {
    $a = array();
    $a[] = [];

    $a[] = [
        "shortName" => "meadow",
        "longName" => "Meadow",
        "color" => '"#a6d8a8"',
        "type" => "grass"
    ];
    
    $a[] = [
        "shortName" => "river",
        "longName" => "River",
        "color" => '"#a6cbd8"',
        "type" => "water"
    ];
    
    $a[] = [
        "shortName" => "mountain",
        "longName" => "Mountain",
        "color" => '"#492020"',
        "type" => "mountain"
    ];
    
    return $a;
}

//------------------------------------------------------------------------
//Building
//------------------------------------------------------------------------

function getBuildingsList() {
    $a = array();
    $a[] = [
        "longName" => "No building",
    ];
    
    $a[] = [
        "color" => 5,
        "shortName" => "lab",
        "longName" => "Laboratory",
        "construction" => [
            "time" => 100,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ]
    ];
    
    $a[] = [
        "color" => 2,
        "shortName" => "plant",
        "longName" => "Small plant",
        "production" => [
            "tool" => [
                "amount" => 3600, //how much per hour
                "resourcesNeeded" => [
                    "rock" => 3600,
                    "wood" => 3600
                ]
            ],
            "wood" => [
                "amount" => 3600,
                "resourcesNeeded" => [
                ]
            ]
        ],
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [ //if the building needs to be near a special type of terrain
            ],
            "nearBuildings" => [ //if the building needs to be near a special type of building
            ]
        ]
    ];
    
    $a[] = [
        "color" => 4,
        "shortName" => "park",
        "longName" => "Small park",
        "happiness" => 10,
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ]
    ];
    
    $a[] = [
        "color" => 1,
        "shortName" => "house",
        "longName" => "Small house",
        "population" => 100,
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ]
    ];
    
    $a[] = [
        "color" => 3,
        "shortName" => "mine",
        "longName" => "Small mine",
        "production" => [
            "rock" => [
                "amount" => 2,
                "resourcesNeeded" => [
                ]
            ],
            "uranium" => [
                "amount" => 2,
                "resourcesNeeded" => [
                ]
            ]
        ],
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ]
    ];
    
    $a[] = [
        "color" => 6,
        "shortName" => "warehouse",
        "longName" => "Warehouse",
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ],
        "landTrade" => true
    ];
    
    $a[] = [
        "color" => 3,
        "shortName" => "farm",
        "longName" => "Small farm",
        "production" => [
            "wheat" => [
                "amount" => 3,
                "resourcesNeeded" => [
                ]
            ],
            "cake" => [
                "amount" => 3,
                "resourcesNeeded" => [
                ]
            ]
        ],
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true
            ],
            "nearTerrains" => [
            ],
            "nearBuildings" => [
            ]
        ]
    ];
    
    $a[] = [
        "color" => 6,
        "shortName" => "dock",
        "longName" => "Docks",
        "construction" => [
            "time" => 10,
            "resources" => [
                "rock" => 100
            ],
            "terrains" => [
                "grass" => true,
                "forest" => true
            ],
            "nearTerrains" => [
                "water" => 1
            ],
            "nearBuildings" => [
            ]
        ],
        "seaTrade" => true
    ];
    return $a;
}

function getBuildingsColors() {
    $a = array();
    $a[] = "house";
    $a[] = "plant";
    $a[] = "mine";
    $a[] = "entertainment";
    $a[] = "research";
    $a[] = "transport";
    return $a;
}

function buildingBonuses($first, $second) {
    $result = [
        "happiness" => 0,
        "production" => 0
    ];
    
    switch ($first) {
        default:
        break;
        
        case 1:
            switch ($second) {
                default:
                break;
                
                case 1:
                break;
                
                case 2:
                $result["production"] = 0.1;
                break;
                
                case 3:
                $result["production"] = 0.1;
                break;
                
                case 4:
                break;
                
                case 5:
                $result["production"] = -0.1;
                break;
                
                case 6:
                break;
            }
        break;
        
        case 2:
            switch ($second) {
                default:
                break;
                
                case 1:
                $result["happiness"] = -5;
                break;
                
                case 2:
                break;
                
                case 3:
                break;
                
                case 4:
                $result["happiness"] = -10;
                break;
                
                case 5:
                $result["production"] = -0.1;
                break;
                
                case 6:
                break;
            }
        break;
        
        case 3:
            switch ($second) {
                default:
                break;
                
                case 1:
                $result["happiness"] = -5;
                break;
                
                case 2:
                $result["production"] = 0.1;
                break;
                
                case 3:
                break;
                
                case 4:
                $result["happiness"] = -10;
                break;
                
                case 5:
                $result["production"] = -0.1;
                break;
                
                case 6:
                break;
            }
        break;
        
        case 4:
            switch ($second) {
                default:
                break;
                
                case 1:
                $result["happiness"] = 5;
                break;
                
                case 2:
                break;
                
                case 3:
                break;
                
                case 4:
                $result["happiness"] = 5;
                break;
                
                case 5:
                break;
                
                case 6:
                break;
            }
        break;
        
        case 5:
            switch ($second) {
                default:
                break;
                
                case 1:
                break;
                
                case 2:
                $result["production"] = 0.1;
                break;
                
                case 3:
                break;
                
                case 4:
                break;
                
                case 5:
                $result["production"] = 0.1;
                break;
                
                case 6:
                break;
            }
        break;
        
        case 6:
            switch ($second) {
                default:
                break;
                
                case 1:
                break;
                
                case 2:
                break;
                
                case 3:
                break;
                
                case 4:
                break;
                
                case 5:
                break;
                
                case 6:
                break;
            }
        break;
    }
    
    return $result;
}

//------------------------------------------------------------------------
//Resources
//------------------------------------------------------------------------

function getResourcesList() {
    $a = array();
    $a[] = [
        "color" => '"#000000"',
        "longName" => "None"
    ];
    
    $a[] = [
        "shortName" => "wood",
        "longName" => "Wood",
        "type" => "material"
    ];
    
    $a[] = [
        "shortName" => "rock",
        "longName" => "Rock",
        "type" => "material",
        "adaptability" => 10,
        "limitUp" => 0.8,
        "limitDown" => 0.2,
        "mineralSolidity" => 50,
        "mineralValue" => 50
    ];
    
    $a[] = [
        "shortName" => "tool",
        "longName" => "Tool",
        "type" => "material"
    ];
    
    $a[] = [
        "shortName" => "wheat",
        "longName" => "Wheat",
        "type" => "glucid",
        "consumptionValue" => 1, //how much is worth 1 ton of wheat
        "adaptability" => 10,
        "limitUp" => 0.8,
        "limitDown" => 0.2,
        "temperature" => 50,
        "precipitation" => 50
    ];
    
    $a[] = [
        "shortName" => "uranium",
        "longName" => "Uranium",
        "type" => "material",
        "color" => '"#73ff2e"',
        "deposit" => true
    ];
    
    $a[] = [
        "shortName" => "cake",
        "longName" => "Cake",
        "type" => "glucid",
        "consumptionValue" => 0.5
    ];
    
    $b = $a;
    
    foreach($b as $r) {
        $a[$r['shortName']] = $r;
    }
    
    return $a;
}

function getResourceId($name) {
    foreach(getResourcesList() as $key => $r) {
        if ($r['shortName'] == $name) {
            return $key;
        }
    }
    
    return 0;
}

function resourcesInRegion($region, $resource) {
	include("serverConnect.php");
	
	$req = $bdd->prepare('SELECT cRegionResources.amount FROM cRegionResources WHERE cRegionResources.region = ? AND cRegionResources.resource = ?');
	$req->execute(array($region, $resource));
	
	if ($data = $req->fetch()) {
		return $data['amount'];
	}
	return 0;
}

function setResourcesInRegion($region, $resource, $amount) {
	include("serverConnect.php");
	
	$req = $bdd->prepare('SELECT cRegionResources.amount FROM cRegionResources WHERE cRegionResources.region = ? AND cRegionResources.resource = ?');
	$req->execute(array($region, $resource));
	
	if ($data = $req->fetch()) {
		$req2 = $bdd->prepare('UPDATE cRegionResources SET amount = ? WHERE cRegionResources.region = ? AND cRegionResources.resource = ?');
		$req2->execute(array($amount, $region, $resource));
	}
	else {
		$req2 = $bdd->prepare('INSERT INTO cRegionResources (region, resource, amount) VALUES(?, ?, ?)');
		$req2->execute(array($region, $resource, $amount));
	}
}

function addResourcesInRegion($region, $resource, $amount) {
	include("serverConnect.php");
	
	$req = $bdd->prepare('SELECT cRegionResources.amount FROM cRegionResources WHERE cRegionResources.region = ? AND cRegionResources.resource = ?');
	$req->execute(array($region, $resource));
	
	if ($data = $req->fetch()) {
		$req2 = $bdd->prepare('UPDATE cRegionResources SET amount = ? WHERE cRegionResources.region = ? AND cRegionResources.resource = ?');
		$req2->execute(array($data['amount'] + $amount, $region, $resource));
	}
	else {
		$req2 = $bdd->prepare('INSERT INTO cRegionResources (region, resource, amount) VALUES(?, ?, ?)');
		$req2->execute(array($region, $resource, $amount));
	}
}

function removeResourcesInRegion($region, $resource, $amount) {
	addResourcesInRegion($region, $resource, -$amount);
}

//------------------------------------------------------------------------
//Influence
//------------------------------------------------------------------------

function getInfluenceGrowth() {
    return 0.01;
}

function influenceInRegion($region, $user) {
    include("serverConnect.php");
    
    $req = $bdd->prepare('SELECT cInfluences.value FROM cInfluences WHERE cInfluences.region = ? AND cInfluences.user = ?');
    $req->execute(array($region, $user));
    
    if ($data = $req->fetch()) {
        return $data['value'];
    }
    return 0;
}

function addInfluenceInRegion($region, $user, $value) {
    include("serverConnect.php");
    
    $req = $bdd->prepare('SELECT cInfluences.value FROM cInfluences WHERE cInfluences.region = ? AND cInfluences.user = ?');
    $req->execute(array($region, $user));
    
    if ($data = $req->fetch()) {
        $v = max(min($data['value'] + $value, 100), 0);
        $req2 = $bdd->prepare('UPDATE cInfluences SET value = ? WHERE cInfluences.region = ? AND cInfluences.user = ?');
        $req2->execute(array($v, $region, $user));
        return $v;
    }
    else {
        $v = max(min($value, 100), 0);
        $req2 = $bdd->prepare('INSERT INTO cInfluences (region, user, value) VALUES(?, ?, ?)');
        $req2->execute(array($region, $user, $v));
        return $v;
    }
}

function removeInfluenceInRegion($region, $user, $value) {
    addInfluenceInRegion($region, $user, -$value);
}

//------------------------------------------------------------------------
//Happiness
//------------------------------------------------------------------------

function getHappinessGrowth() {
    return 10;
}

//------------------------------------------------------------------------
//Population
//------------------------------------------------------------------------

function getPopulationGrowth() {
    return 0.01;
}

function getConsumption() {
    $a = [
        "glucid" => [
            "amount" => 0.01, //1 ton / pop / h
            "malus" => 100 //if not enough 
        ]
    ];
    
    return $a;
}

//------------------------------------------------------------------------
//Trade
//------------------------------------------------------------------------

function breakTrade($transportId) {
    include("serverConnect.php");
    
    $req = $bdd->prepare('SELECT * FROM cTransports WHERE id = ?');
    $req->execute(array($transportId));

    if (!($data = $req->fetch())) {
        return;
    }
    
    if ($data['way'] == 0) {
        addResourcesInRegion($data['regionStart'], $data['resource'], $data['amount']);
    }
    
    $req = $bdd->prepare('DELETE FROM cTransports WHERE cTransports.id = ?');
    $req->execute(array($transportId));
    
    //TODO : Remove honor
    
    rebuildRegionSets();
}

function mergeRegionSets($a, $b) {
    include("serverConnect.php");
    
    $setA = 0;
    $setB = 0;
    
    $req = $bdd->prepare('SELECT id FROM cSets WHERE region = ?');
    $req->execute(array($a));

    if ($data = $req->fetch()) {
        $setA = $data["id"];
    }
    
    $req = $bdd->prepare('SELECT id FROM cSets WHERE region = ?');
    $req->execute(array($b));

    if ($data = $req->fetch()) {
        $setB = $data["id"];
    }
    
    if ($setA == 0 && $setB == 0) {
        $req = $bdd->prepare('SELECT MAX(id) AS M FROM cSets');
        $req->execute(array());
        $data = $req->fetch();
        
        $newId = nullIsZero($data['M']) + 1;
        
        $req = $bdd->prepare('INSERT INTO cSets (region, id) VALUES(?, ?)');
        $req->execute(array($a, $newId));
        
        $req = $bdd->prepare('INSERT INTO cSets (region, id) VALUES(?, ?)');
        $req->execute(array($b, $newId));
    }
    else if ($setA == 0) {
        $req = $bdd->prepare('INSERT INTO cSets (region, id) VALUES(?, ?)');
        $req->execute(array($a, $setB));
    }
    else if ($setB == 0) {
        $req = $bdd->prepare('INSERT INTO cSets (region, id) VALUES(?, ?)');
        $req->execute(array($b, $setA));
    }
    else if ($setA != $setB){
        $req = $bdd->prepare('UPDATE cSets SET id = ? WHERE id = ?');
        $req->execute(array(min($setA, $setB), max($setA, $setB)));
        
    }
}

function rebuildRegionSets() {
    include("serverConnect.php");
    
    $req = $bdd->prepare('DELETE FROM cSets');
    $req->execute(array());
    
    $req = $bdd->prepare('SELECT * FROM cTransports');
    $req->execute(array());

    while ($data = $req->fetch()) {
        mergeRegionSets($data['regionStart'], $data['regionEnd']);
    }
}

?>