# THIS IS A SOURCE CODE FILE FROM I'M NOT EVEN HUMAN THE GAME.
# IT COULD BE USED IN A DIFFERENT PIECE OF SOFTWARE ( LIKE A
# DIFFERENT GAME ), BUT IT WAS ORIGINALLY WRITTEN FOR I'M NOT
# EVEN HUMAN THE GAME.

# THE DEVELOPERS OF THE GAME ARE : (C) J.Y.AMIHUD, AYYZEE AND 
# OTHER CONTRIBUTORS. THIS AND OTHER FILES IN THIS GAME,
# UNLESS SPECIFICALLY NOTED, COULD BE USED UNDER THE TERMS OF
# GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER VERSION.

import os
import json
import cairo

from modules import ui

def draw(game, outlayer, x, y, w, h, grid=True):

    """This function will draw the level it self"""

    x = int(x)
    y = int(y)
    w = int(w)
    h = int(h)

    # To make it a bit more nice, I will use a separate image
    # layer for the level.

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,w,h)
    layer = cairo.Context(surface)
    layer.set_antialias(cairo.ANTIALIAS_NONE)


    if game.current["testing"]:
        ui.color(game, layer, "red")
        layer.rectangle(0,0,w-1,h-1)
        layer.stroke()

    sidex = 64
    sidey = 36
    offsetx = int(sidex / 2)
    offsety = int(sidey / 2)

    # moving the game world
    if game.current["MMB"]:
        game.current["camera"][0] += (game.current["mx"] - game.previous["mx"])
        game.current["camera"][1] += (game.current["my"] - game.previous["my"])
        
    # Drawing the cells
    for th in range(int(h/offsety)+4):
        offx = game.current["camera"][0] % sidex
        offy = game.current["camera"][1] % sidey
        if th % 2 == 0:
            offx += offsetx
            
        for tw in range(int(w/sidex)+3):

            drawx = (tw-2)*sidex+offx
            drawy = (th-3)*offsety+offy
            
            ui.color(game, layer, "#00FF00")
            ui.image(game, layer,
                     drawx,
                     drawy,
                     "assets/grid.png", color=True)

            # THIS MAGICAL MATH GIVES US THE CURRENT CELL
           
            xaddr = 0-int( (game.current["camera"][0] - drawx) / sidex )
            yaddr = 0-int( (game.current["camera"][1] - drawy) / offsety )
            
            ui.text(game,layer, str(xaddr)+":"+str(yaddr),
                    offsetx+((tw-2)*sidex+offx),
                    -4+offsety+((th-3)*offsety+offy),
                    align="center")

    

    # Drawing the world to the outlayer
    outlayer.set_source_surface(surface, x , y)
    outlayer.paint()

def generate_empty_chunk(game):

    """This function will generate empty chunks"""

    chunkx = 50
    chunky = 50

    sidex = 62
    sidey = 36
    offsetx = int(sidex / 2)
    offsety = int(sidey / 2)

    # The chunk will be more or less square

    #  [ 1 ][ 2 ][ 3 ]
    #    [ 4 ][ 5 ][ 6 ]
    #  [ 7 ][ 8 ][ 9 ]

    
