import pygame
from pygame.locals import *
from image import *
from sys import exit
from userinput import *
from random import randint, uniform

def playSettler(screen):
    grid_width = 80
    grid_size = (8,6)
    background = loadImage('settledmap.png').convert_alpha()
    population = 10
    food = 0
    building_materials = 10
    labor = [.2,.3,.3,.2, 0.0]
    stats_font = pygame.font.SysFont('Arial', 18)
    

    end_turn = loadImage('endturn.png')
    end_rect = Rect((330,410), (end_turn.get_width(), end_turn.get_height()))

    labor_button = loadImage('laborbutton.png')
    labor_rect = Rect((200, 410), (labor_button.get_width(), labor_button.get_height()))
    
    hut_clicked = False
    farm_clicked = False
    pit_clicked = False
    current_square = None
    turn = 1


    
    grid = []
    for x in range(grid_size[0]):
        row = [0]*grid_size[1]
        grid.append(row)

    #non-playable grid spots
    grid[0][0] = -1
    grid[0][1] = -1
    grid[0][2] = -1

    grid[3][5] = -1
    grid[4][5] = -1
    grid[5][5] = -1
    grid[6][5] = -1
    grid[7][5] = -1
    grid[7][4] = -1

    grid[1][0] = -1
    grid[1][1] = -1
    grid[1][2] = -1
    grid[1][3] = -1
    grid[2][3] = -1
    grid[2][4] = -1
    grid[2][5] = -1





    note_list = ['start']
    num_list = [0]
    x_button = None
    
    while True:
        clicked = False
        right_clicked = False
        
        
        for event in pygame.event.get():
            standardInput(event, screen)
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    clicked = True
                elif event.button == 3:
                    right_clicked = True


        mouse_pos = pygame.mouse.get_pos()

        if clicked and end_rect.collidepoint(mouse_pos) and not x_button:
            turn, background = changeTurn(turn)
            food, population, building_materials, note_list, num_list = makeChanges(grid,food,population,turn,building_materials,labor)

        if not x_button:   
            clicked, hut_clicked, farm_clicked, pit_clicked = clickBuildings(mouse_pos, clicked, right_clicked, hut_clicked, farm_clicked, pit_clicked, building_materials)
        

        screen.fill((255,255,255))
        screen.blit(background, (0,0))
        drawGrid(grid_width, grid_size, screen)

        if hut_clicked or farm_clicked or pit_clicked:
            current_square = highlightBox(screen, grid_width, mouse_pos, grid)

        if (hut_clicked or farm_clicked or pit_clicked) and clicked and current_square:
            building_materials = setBuilding(grid, current_square,
                                             hut_clicked, farm_clicked, pit_clicked,
                                             building_materials)
            hut_clicked = False
            farm_clicked = False
            pit_clicked = False

        if clicked and x_button and x_button.collidepoint(mouse_pos):
            note_list.pop(0)
            x_button = None

        if clicked and not x_button and labor_rect.collidepoint(mouse_pos):
            labor = allocateLabor(screen, labor)
            
        

        if population >= 100:
            note_list = ['win']
            num_list = [0]
        showBuildings(screen, grid, grid_width)
        if len(note_list) != 0:
            x_button = displayMessage(screen, note_list, num_list)
        showStats(screen, population, stats_font, turn, food, building_materials)
        showBuildBar(screen, building_materials)
        screen.blit(end_turn, end_rect)
        screen.blit(labor_button, labor_rect)
        showDraggedItems(screen, mouse_pos, hut_clicked, farm_clicked, pit_clicked)
        pygame.display.update()



def changeTurn(turn):
    turn = (turn + 1) % 4
    if turn == 0:
        background = loadImage('springbackground.png')
    if turn == 1:
        background = loadImage('settledmap.png')
    if turn == 2:
        background = loadImage('fallbackground.png') 
    if turn == 3:
        background = loadImage('winterbackground.png')
    return turn, background

def makeChanges(grid, food, population, turn, building_materials, labor):
    
    notes_list = []
    num_list = []


    
    num_huts, num_farms, num_pits = countBuildings(grid)
    hut_labor = float(labor[0]*population)/max(num_huts,1)
    farm_labor = float(labor[1]*population)/max(num_farms,1)
    pit_labor = float(labor[2]*population)/max(num_pits,1)
    gathering_labor = labor[3]*population


    storage_constant = 20
    pit_stored = storage_constant*num_pits*min(pit_labor,10)
    hut_stored = storage_constant*num_huts*hut_labor*.2
    food_stored = int(pit_stored + hut_stored)



    growth_constant = None
    consumption_constant = 3
    if turn == 0:
        growth_constant = 10
    elif turn == 1:
        growth_constant = 15
    elif turn == 2:
        growth_constant = 20
    elif turn == 3:
        growth_constant = 2
        
    food_grown = num_farms*growth_constant*min(farm_labor, 10)
    food_consumed = consumption_constant*population
    surplus_food = max(food + food_grown - food_consumed,0)
    hungry_people = max((food_consumed-food-food_grown)/consumption_constant,0)
    food_wasted = max(surplus_food- food_stored, 0)

    if food_wasted:
        notes_list.append('wasted')
        num_list.append(int(food_wasted))
    



    population_constant = 1.1
    population = int(population**population_constant)
    housing = int( num_huts*(6*min(hut_labor, 4) + 1))
    surplus_housing = max(housing - population,0)
    surplus_population = max(population - housing,0)

    additional_pop = 0
    if surplus_population:
        if turn == 3:
            died = int(surplus_population*.75)
            additional_pop -= died

            notes_list.append('cold')
            num_list.append(died)
        else:
            died = int(surplus_population*.5)
            additional_pop -= died
            if died > 0:
                notes_list.append('overcrowding')
                num_list.append(died)

    if surplus_housing:
        additional_pop += min(population*.1, surplus_housing*.1)


    if surplus_food:
        additional_pop += int(min(food_stored, surplus_food)*.05)
        
    if hungry_people:
        died = max(int(hungry_people*.5),1)
        additional_pop -= died
        notes_list.append('starvation')
        num_list.append(died)

    gathering_constant = 2
    wood_gathered = gathering_constant*gathering_labor
    


    population = max(int(population + additional_pop),0)
    food = max(min(int(food + food_grown - food_consumed), int(food_stored)),0)
    building_materials = max(int(building_materials + wood_gathered),0)
    
    

    return food, population, building_materials, notes_list, num_list


            
        
    

def setBuilding(grid, current_square, hut_clicked, farm_clicked, pit_clicked, building_materials):
    if current_square:
        if hut_clicked:
            grid[current_square[0]][current_square[1]] = 1
            building_materials -= 5
        if farm_clicked:
            grid[current_square[0]][current_square[1]] = 2
            building_materials -= 3
        if pit_clicked:
            grid[current_square[0]][current_square[1]] = 3
            building_materials -= 2
    return building_materials


def countBuildings(grid):
    num_hut = 0
    num_farm = 0
    num_pit = 0

    for r in range(len(grid)):
        for c in range(len(grid[0])):
            val = grid[r][c]
            if val == 1:
                num_hut += 1
            elif val == 2:
                num_farm += 1
            elif val == 3:
                num_pit += 1

    return num_hut, num_farm, num_pit


def clickBuildings(mouse_pos, clicked, right_clicked, hut_clicked, farm_clicked, pit_clicked, building_materials):
    hut_rect = Rect((10,10),(60,60))
    farm_rect = Rect((10,90),(60,60))
    pit_rect = Rect((10,170), (60,60))

    if clicked and hut_clicked and hut_rect.collidepoint(mouse_pos):
        hut_clicked = False
        clicked = False
    if clicked and farm_clicked and farm_rect.collidepoint(mouse_pos):
        farm_clicked = False
        clicked = False
    if clicked and pit_clicked and pit_rect.collidepoint(mouse_pos):
        pit_clicked = False
        clicked = False
    if right_clicked:
        hut_clicked = False
        farm_clicked = False
        pit_clicked = False

    
    if clicked and hut_rect.collidepoint(mouse_pos) and building_materials >=5:
        hut_clicked = True
        farm_clicked = False
        pit_clicked = False
    if clicked and farm_rect.collidepoint(mouse_pos) and building_materials >=3:
        hut_clicked = False
        farm_clicked = True
        pit_clicked = False
    if clicked and pit_rect.collidepoint(mouse_pos)and building_materials >=2:
        hut_clicked = False
        farm_clicked = False
        pit_clicked = True

    return clicked, hut_clicked, farm_clicked, pit_clicked
