""" The configuration bits of TileStache.

TileStache configuration is stored in JSON files, and is composed of two main
top-level sections: "cache" and "layers". There are examples of both in this
minimal sample configuration:

    {
      "cache": {"name": "Test"},
      "layers": {
        "example": {
            "provider": {"name": "mapnik", "mapfile": "examples/style.xml"},,
            "projection": "spherical mercator"
        }
      }
    }

The contents of the "cache" section are described in greater detail in the
TileStache.Caches module documentation. Here is a different sample:

    "cache": {
      "name": "Disk",
      "path": "/tmp/stache",
      "umask": "0000"
    }

The "layers" section is a dictionary of layer names which are specified in the
URL of an individual tile. More detail on the configuration of individual layers
can be found in the TileStache.Core module documentation. Another sample:

    {
      "cache": ...,
      "layers":
      {
        "example-name":
        {
            "provider": { ... },
            "metatile": { ... },
            "preview": { ... },
            "stale lock timeout": ...,
            "projection": ...
        }
      }
    }

Configuration also supports these additional settings:

- "logging": one of "debug", "info", "warning", "error" or "critical", as
  described in Python's logging module: http://docs.python.org/howto/logging.html

- "index": configurable index pages for the front page of an instance.
  A custom index can be specified as a filename relative to the configuration
  location. Typically an HTML document would be given here, but other kinds of
  files such as images can be used, with MIME content-type headers determined
  by mimetypes.guess_type. A simple text greeting is displayed if no index
  is provided.

In-depth explanations of the layer components can be found in the module
documentation for TileStache.Providers, TileStache.Core, and TileStache.Geography.
"""

import sys
import logging
from os.path import join as pathjoin
from mimetypes import guess_type
from json import dumps

try:
    from json import dumps as json_dumps
except ImportError:
    from simplejson import dumps as json_dumps

from ModestMaps.Geo import Location
from ModestMaps.Core import Coordinate

from . import Core
from . import Caches
from . import Providers
from . import Geography
from . import PixelEffects

from .py3_compat import reduce, urljoin, urlparse, urlopen

class Configuration:
    """ A complete site configuration, with a collection of Layer objects.

        Attributes:

          cache:
            Cache instance, e.g. TileStache.Caches.Disk etc.
            See TileStache.Caches for details on what makes
            a usable cache.

          layers:
            Dictionary of layers keyed by name.

            When creating a custom layers dictionary, e.g. for dynamic
            layer collections backed by some external configuration,
            these dictionary methods must be provided for a complete
            collection of layers:

              keys():
                Return list of layer name strings.

              items():
                Return list of (name, layer) pairs.

              __contains__(key):
                Return boolean true if given key is an existing layer.

              __getitem__(key):
                Return existing layer object for given key or raise KeyError.

          dirpath:
            Local filesystem path for this configuration,
            useful for expanding relative paths.

        Optional attribute:

          index:
            Mimetype, content tuple for default index response.
    """
    def __init__(self, cache, dirpath):
        self.cache = cache
        self.dirpath = dirpath
        self.layers = {}

        self.index = 'text/plain', 'TileStache bellows hello.'

class Bounds:
    """ Coordinate bounding box for tiles.
    """
    def __init__(self, upper_left_high, lower_right_low):
        """ Two required Coordinate objects defining tile pyramid bounds.

            Boundaries are inclusive: upper_left_high is the left-most column,
            upper-most row, and highest zoom level; lower_right_low is the
            right-most column, furthest-dwn row, and lowest zoom level.
        """
        self.upper_left_high = upper_left_high
        self.lower_right_low = lower_right_low

    def excludes(self, tile):
        """ Check a tile Coordinate against the bounds, return true/false.
        """
        if tile.zoom > self.upper_left_high.zoom:
            # too zoomed-in
            return True

        if tile.zoom < self.lower_right_low.zoom:
            # too zoomed-out
            return True

        # check the top-left tile corner against the lower-right bound
        _tile = tile.zoomTo(self.lower_right_low.zoom)

        if _tile.column > self.lower_right_low.column:
            # too far right
            return True

        if _tile.row > self.lower_right_low.row:
            # too far down
            return True

        # check the bottom-right tile corner against the upper-left bound
        __tile = tile.right().down().zoomTo(self.upper_left_high.zoom)

        if __tile.column < self.upper_left_high.column:
            # too far left
            return True

        if __tile.row < self.upper_left_high.row:
            # too far up
            return True