import sys

sys.path.insert(0, './../../')

from globals import G
import random
import world_map.seas as SEAS


def default(sea):

    recalculate, hole = are_holes_present(sea)

    if recalculate and sea.size > 1:
        cells_to_try_to_dry = []
        for i in sea.cells:
            if i.get_elevation() == sea.water_level:
                cells_to_try_to_dry.append(i)

        cell_to_dry = random.choice(cells_to_try_to_dry)
        if are_holes_connected_not_only_with_cell_to_dry(sea, i):
            sea.dry_one_cell(cell_to_dry)
            if sea.is_deleted:
                return
        else:
            sea.max_size -= 1
            sea.dry_one_cell(cell_to_dry)
            SEAS.sea('new', [hole, 1])

    elif recalculate:
        hole_elevation = 4
        for i in sea.coast:
            if i.get_elevation() < hole_elevation:
                holes = [i]
                hole_elevation = i.get_elevation()
            else:
                holes.append(i)

        sea.move_its_only_cell(random.choice(holes))

    return recalculate

def are_holes_present(sea):
    for i in sea.coast:
        if i.get_elevation() < sea.water_level:
            return True, i
    return False, None

def are_holes_connected_not_only_with_cell_to_dry(sea, cell_to_dry):
    holes = []
    for i in sea.coast:
        if i.get_elevation() < sea.water_level:
            holes.append(i)

    for the_hole in holes:
        hole_adj = the_hole.get_adjacent('all')
        for i in hole_adj:
            adj_cell = G.world_map.get_cell(i)
            if adj_cell in sea.cells and adj_cell != cell_to_dry:
                return True

    return False

check_holes_list = [default]