import os
import pygame
from kb import tractor_kb
import pytholog as pl
import random
from config import TILE_SIZE, FREE_TILES

class Tile(pygame.sprite.Sprite):

    def __init__(self, id, field):
        super().__init__()
        self.id = id
        x = id%16
        y = id//16

        self.field = field

        # temporary solution to have vegetables act as obstacles
        if random.randint(1, 10) % FREE_TILES == 0:
            vegetables = tractor_kb.query(pl.Expr("warzywo(Nazwa_warzywa)"))
            random_vegetable = vegetables[random.randint(0, len(vegetables)-1)]['Nazwa_warzywa']

            if random_vegetable in {'cebula','pietruszka','bób', 'dynia','ziemniak'}:
                random_vegetable = 'marchew'

            self.set_type(random_vegetable)
            self.water_level = random.randint(1, 5) * 10
            self.stage = 'planted' # wczesniej to była self.faza = 'posadzono' ale stwierdzilem ze lepiej po angielsku???
        else:
            if random.randint(1, 10) % 3 == 0:
                self.set_type('water')
                self.water_level = 100
                self.stage = 'no_plant'
            else:
                self.set_type('grass')
                self.water_level = random.randint(1, 5) * 10
                self.stage = 'no_plant'
        

        self.rect = self.image.get_rect()
        self.rect.topleft = (x * TILE_SIZE, y * TILE_SIZE)
    

    def draw(self, surface):
        self.tiles.draw(surface)

    def set_type(self, type):
        self.type = type
        if self.type == 'grass':
            image_path = "images/grass.png"
        elif self.type == 'water':
            image_path = "images/water.png"
        else:
            image_path = f"images/vegetables/{self.type}.png"
            if not os.path.exists(image_path):
                image_path = "images/question.jpg"
        
        self.image = pygame.image.load(image_path).convert()
        self.image = pygame.transform.scale(self.image, (TILE_SIZE, TILE_SIZE))