#!python3
#
# Read a GBIF download and generate a pixel map layer.
#
# Colour the pixels in the matrix according to density.
#

# You also need a base map:
#   curl -o base-east.png 'http://tile.gbif-dev.org/4326/omt/0/0/0@1800p.png?style=gbif-classic&srs=EPSG:4326'
#   curl -o base-west.png 'http://tile.gbif-dev.org/4326/omt/0/1/0@1800p.png?style=gbif-classic&srs=EPSG:4326'
#   montage base-west.png base-east.png -geometry +0+0 -tile 2x1 base.png
#
# And might then overlay the result on it:
#   composite -gravity center occurrences.png base.png map.png

import csv
import numpy as np
from PIL import Image

from dwca.read import DwCAReader
from dwca.darwincore.utils import qualname as qn

with DwCAReader('0112875-230224095556074.zip') as dwca:

    width = 3600
    height = 1800
    size = (width, height)

    counts = [0] * width * height
    matrix = [(0,0,0,0)] * width * height

    i = 0
    for row in dwca:
        (lat, lng) = (row.data[qn('decimalLatitude')], row.data[qn('decimalLongitude')])

        if lat != '':
            x = int(height - round((float(lat) + 90) / 180.0 * height))
            y = int(round((float(lng) + 180) / 360.0 * width))
            counts[y * width + x] += 1
            i += 1

        if i % 1000 == 0:
            print("Processed", i)

    print("Processed", i)

    for y in range(height):
        for x in range(width):
            count = counts[y * width + x]

            if count > 0:
                #                [total <=    10] { dot-fill: #FFFF00;  }
                # [total >    10][total <=   100] { dot-fill: #FFCC00;  }
                # [total >   100][total <=  1000] { dot-fill: #FF9900;  }
                # [total >  1000][total <= 10000] { dot-fill: #FF6600;  }
                # [total > 10000]                 { dot-fill: #D60A00;  }

                matrix[y * width + x] = (0xFF, 0xFF, 0x00, 0xFF)
                if (count > 10):
                    matrix[y * width + x] = (0xFF, 0xCC, 0x00, 0xFF)
                if (count > 100):
                    matrix[y * width + x] = (0xFF, 0x99, 0x00, 0xFF)
                if (count > 1000):
                    matrix[y * width + x] = (0xFF, 0x66, 0x00, 0xFF)
                if (count > 10000):
                    matrix[y * width + x] = (0xD6, 0x0A, 0x00, 0xFF)

image = Image.new("RGBA", size)
image.putdata(matrix)
image.save('occurrences.png')
