import pygame
from pygame.locals import *
import time
from userinput import *

def loadImage(filename):
    return pygame.image.load("Images/" + filename)


def drawGrid(grid_width, grid_size, screen):
    color = (0,0,0)
    top_height = grid_size[1]*grid_width
    for x in range(screen.get_width()/grid_width+1):
        pygame.draw.line(screen, color, (x*grid_width, 0), (x*grid_width, top_height))

    for x in range(top_height/grid_width+1):
        pygame.draw.line(screen, color, (0, x*grid_width), (screen.get_width(), x*grid_width))

def colorAdjacentSquares(screen, adjacent_color, player_pos, grid_width, grid_size, mouse_pos, clicked):
    moved = False
    for x in range(player_pos[0]-1, player_pos[0]+2):
        for y in range(player_pos[1] -1, player_pos[1]+2):
            if 0 <= x < grid_size[0] and 0 <= y < grid_size[1] and not (x == player_pos[0] and y ==player_pos[1]):
                rect = Rect(x*grid_width, y*grid_width, grid_width, grid_width)
                pygame.draw.rect(screen, adjacent_color, rect, 4)
                if rect.collidepoint(mouse_pos):
                    new_color = (adjacent_color[0]*.5, adjacent_color[1]*.5, adjacent_color[2]*.5)
                    pygame.draw.rect(screen, new_color, rect, 6)
                    if clicked:
                        new_pos = x,y
                        moved = True

    screen.set_clip()
    if moved:
        return new_pos, moved
    return player_pos, moved


def showFood(screen, font, food):
    loc = (300, 430)
    message = "Food: " + str(food)
    surface = font.render(message, True, (0,0,0))
    screen.blit(surface, loc)

def showGainedMessage(screen, font, food_gained, lost):
    loc = (185, 400)
    message = "You hunted " + str(food_gained) + " units of food."
    if lost:
        message = "You consumed " + str(food_gained) + " units of food."
    surface = font.render(message, True, (0,0,0))
    screen.blit(surface, loc)
    pygame.display.update()
    pygame.time.wait(2000)

def showSettledMessage(screen, font):
    loc = (180, 400)
    message = "You have run out of food. You must settle."

    surface = font.render(message, True, (0,0,0))
    screen.blit(surface, loc)

    return True

def showMapofSquare(screen, player_pos, grid_width):
    xpos = player_pos[0]*grid_width
    ypos = player_pos[1]*grid_width
    square = screen.subsurface((xpos,ypos), (grid_width, grid_width))
    copy = square.copy()
    copy = pygame.transform.scale(copy, (140,140))
    screen.blit(copy, (470,330))


def showStats(screen, population, font, turn, food, building_materials):
    stats = loadImage('statsscreen.png')
    stats = pygame.transform.scale(stats, (250, 150))
    screen.blit(stats, (screen.get_width()-stats.get_width(),
                        screen.get_height()-stats.get_height()))

    pop_m = 'Population: ' + str(population)
    pop_s = font.render(pop_m, True, (255,255,255))
    screen.blit(pop_s, (510, 415))

    food_m = 'Food: ' + str(food)
    food_s = font.render(food_m, True, (255,255,255))
    screen.blit(food_s, (520, 435))

    build_m = 'Building Materials: ' + str(building_materials)
    build_s = font.render(build_m, True, (255,255,255))
    screen.blit(build_s, (485, 455))

    season_m = None
    if turn == 0:
        season_m = 'Spring'
    if turn == 1:
        season_m = 'Summer'
    if turn == 2:
        season_m = 'Autumn'
    if turn == 3:
        season_m = 'Winter'
    season_s = font.render(season_m, True, (255,255,255))
    screen.blit(season_s, (520, 395))
    

def showBuildBar(screen, building_materials):
    hut = loadImage('hut.png')
    farm = loadImage('farm.png')
    storagepit = loadImage('storagepit.png')
    bar = loadImage('buildbar.png')
    dark = loadImage('darken.png')

    screen.blit(bar, (0,0))        
    screen.blit(hut, (10, 10))
    screen.blit(farm, (10, 90))
    screen.blit(storagepit, (10, 170))

    if building_materials < 5:
        screen.blit(dark, (10,10))
        if building_materials < 3:
            screen.blit(dark, (10,90))
            if building_materials < 2:
                screen.blit(dark, (10,170))

def showDraggedItems(screen, mouse_pos, hut_clicked, farm_clicked, pit_clicked):
    if hut_clicked:
        item = loadImage('hut.png')
        screen.blit(item, (mouse_pos[0]-item.get_width()/2, mouse_pos[1]-item.get_height()/2))
    if farm_clicked:
        item = loadImage('farm.png')
        screen.blit(item, (mouse_pos[0]-item.get_width()/2, mouse_pos[1]-item.get_height()/2))
    if pit_clicked:
        item = loadImage('storagepit.png')
        screen.blit(item, (mouse_pos[0]-item.get_width()/2, mouse_pos[1]-item.get_height()/2))
        
def highlightBox(screen, grid_width, mouse_pos, grid):
    xpos = mouse_pos[0] / grid_width
    ypos = mouse_pos[1] / grid_width
    if grid[xpos][ypos] >= 0:
        box = Rect((xpos*grid_width, ypos*grid_width), (grid_width, grid_width))
        pygame.draw.rect(screen, (255,0,0), box, 6)
        return xpos, ypos
    return None

def showBuildings(screen, grid, grid_width):
    for x in range(len(grid)):
        for y in range(len(grid[0])):
            if grid[x][y]==0:
                pass
            elif grid[x][y]==1:
                item = loadImage('hut.png')
                screen.blit(item, (x*grid_width+10, y*grid_width+10))
            elif grid[x][y]==2:
                item = loadImage('farm.png')
                screen.blit(item, (x*grid_width+10, y*grid_width+10))
            elif grid[x][y]==3:
                item = loadImage('storagepit.png')
                screen.blit(item, (x*grid_width+10, y*grid_width+10))


def displayMessage(screen, notes_list, num_list):
    font = pygame.font.SysFont('Arial', 16)
    line_width = 20
    ml = []
    message = notes_list[0]
    number = num_list[0]

    if message == 'start':
        ml.append('Congratulations on starting your settlement!')
        ml.append("You'll notice that you have the option to build" )
        ml.append("huts, farms, and storage pits.  You can find ")
        ml.append("these buildings on the left of the screen.")
        ml.append("You can also assign jobs to your citizens by")
        ml.append("clicking the 'DIVIDE LABOR' button below.")
        ml.append("You can see stats on your settlement in the ")
        ml.append("bottom right corner.")
        ml.append("When you're done with all you want to do, click ")
        ml.append("on the 'END TURN' button to advance to the ")
        ml.append("next season.")
        ml.append("You could start by building a hut and a farm.")
        ml.append("")
    if message == 'overcrowding':
        ml.append("")
        ml.append("You lost " + str(number) + " citizens because of")
        ml.append("unsanitary conditions due to overcrowding.")
        ml.append("")
        ml.append("You should build more housing.")
        
    if message == 'cold':
        ml.append("")
        ml.append("You lost " + str(number) + " citizens because of")
        ml.append("overexposure to the cold.")
        ml.append("")
        ml.append("You should build more housing.")
    if message == 'wasted':
        ml.append("")
        ml.append("You wasted " + str(number) + " units of food because")
        ml.append("there was not room to store it all.")
        ml.append("")
    if message == 'starvation':
        ml.append("")
        ml.append("You lost " + str(number) + " citizens due to malnutrition")
        ml.append("")
        ml.append("You should build more farms, reallocate your")
        ml.append("labor or store your food better.")
    if message == 'win':
        ml.append("Congratulations!")
        ml.append("Your settlement has reached a population of 100!")
        ml.append("")
        ml.append("")
        ml.append("")
        ml.append("(This concludes our demo. Please exit the game.)")
    renderText(screen, font, ml, line_width)
    rect = Rect((473, 103), (28,22))
    return rect



def renderText(screen, font, message_list, line_width):
    xpos = 185
    ypos = 115
    background = loadImage('messagebackground.png')
    screen.blit(background, (0,0))
    line = 0
    for message in message_list:
        surface = font.render(message, True, ((0,0,0)))
        pos = xpos, ypos + line*line_width
        screen.blit(surface, pos)

        line += 1

def allocateLabor(screen, labor_list):
    background = loadImage('allocatescreen.png')
    up_pic = loadImage('uparrow.png')
    down_pic = loadImage('downarrow.png')
    

    font = pygame.font.SysFont('Arial', 18)

    size = (40,40)
    xpos = 420
    ypos = 128
    x_gap = 40
    y_gap = 38
    up_h = Rect((xpos, ypos), size)
    down_h = Rect((xpos+x_gap, ypos), size)
    
    up_f = Rect((xpos, ypos+y_gap), size)
    down_f = Rect((xpos+x_gap, ypos+y_gap), size)
    
    up_s = Rect((xpos, ypos+y_gap*2), size)
    down_s = Rect((xpos+x_gap, ypos+y_gap*2), size)
    
    up_g = Rect((xpos, ypos+y_gap*3), size)
    down_g = Rect((xpos+x_gap, ypos+y_gap*3), size)



    x2pos = 180
    hpos = Rect((x2pos, ypos), size)
    fpos = Rect((x2pos, ypos+y_gap), size)
    spos = Rect((x2pos, ypos+y_gap*2), size)
    gpos = Rect((x2pos, ypos+y_gap*3), size)
    upos = Rect((x2pos, ypos+y_gap*4), size)

    x3pos = 350
    size2 = (55, 20)
    hwpos = Rect((x3pos, ypos), size2)
    fwpos = Rect((x3pos, ypos+y_gap), size2)
    swpos = Rect((x3pos, ypos+y_gap*2), size2)
    gwpos = Rect((x3pos, ypos+y_gap*3), size2)
    uwpos = Rect((x3pos, ypos+y_gap*4), size2)


    

    pygame.draw.rect(screen, (0,0,0), Rect((450,320),(40,40)))
    ok_rect = Rect((450,320),(40,40))
    while True:
        clicked = False
        
        for event in pygame.event.get():
            standardInput(event, screen)
            if event.type == MOUSEBUTTONDOWN:
                clicked = True
                    
        mouse_pos = pygame.mouse.get_pos()

        if clicked and ok_rect.collidepoint(mouse_pos):
            return labor_list

        if clicked and up_h.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 0, 1)
        if clicked and down_h.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 0, -1)
        if clicked and up_f.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 1, 1)
        if clicked and down_f.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 1, -1)
        if clicked and up_s.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 2, 1)
        if clicked and down_s.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 2, -1)
        if clicked and up_g.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 3, 1)
        if clicked and down_g.collidepoint(mouse_pos):
            labor_list = changeLabor(labor_list, 3, -1)
        


        h = "Hut tending:                       " + str(labor_list[0]*100) + "%"
        f = "Farming:                             " + str(labor_list[1]*100) + "%"
        s = "Food storing:                     " + str(labor_list[2]*100) + "%"
        g = "Wood gathering:                " + str(labor_list[3]*100) + "%"
        u = "Free labor:                          " + str(labor_list[4]*100)+ "%"
        
        hsur = font.render(h, True, (0,0,0))
        fsur = font.render(f, True, (0,0,0))
        ssur = font.render(s, True, (0,0,0))
        gsur = font.render(g, True, (0,0,0))
        usur = font.render(u, True, (0,0,0))
        
        screen.blit(background, (0,0))
        
        screen.blit(up_pic, up_h)
        screen.blit(up_pic, up_f)
        screen.blit(up_pic, up_s)
        screen.blit(up_pic, up_g)

        screen.blit(down_pic, down_h)
        screen.blit(down_pic, down_f)
        screen.blit(down_pic, down_s)
        screen.blit(down_pic, down_g)


        pygame.draw.rect(screen, (255,255,255), hwpos)
        pygame.draw.rect(screen, (255,255,255), fwpos)
        pygame.draw.rect(screen, (255,255,255), swpos)
        pygame.draw.rect(screen, (255,255,255), gwpos)
        pygame.draw.rect(screen, (255,255,255), uwpos)
        

        screen.blit(hsur, hpos)
        screen.blit(fsur, fpos)
        screen.blit(ssur, spos)
        screen.blit(gsur, gpos)
        screen.blit(usur, upos)
        
        
        pygame.display.update()


def changeLabor(labor_list, kind, change):
    change_magnitude = .05
    free = 4

    potential_end = labor_list[kind] + change_magnitude*change
    potential_free = labor_list[free] - change_magnitude*change

    print potential_end, potential_free
    if 0 <= potential_free <= 1.0 and 0 <= potential_end <= 1.0:
        labor_list[free] = potential_free
        labor_list[kind] = potential_end
    if potential_free < 0 or potential_end > 1.0:
        change = min(labor_list[free], 1.0-labor_list[kind])
        labor_list[free] = round(labor_list[free]-change, 3)
        labor_list[kind] = round(labor_list[kind]+change, 3)

    if potential_free > 1.0 or potential_end < 0:
        change = min(labor_list[kind], 1.0-labor_list[free])
        labor_list[free] = round(labor_list[free]+change, 3)
        labor_list[kind] = round(labor_list[kind]-change, 3)

    if labor_list[free] < 0.001:
        labor_list[free] = 0.0
    if labor_list[kind] <.001:
        labor_list[kind] = 0.0
        

    

    return labor_list
        
    
      

    
    
