import json
import random
import requests
import pygame as pg
pg.init()

SCREEN_WIDTH = 864
SCREEN_HEIGHT = 768

clock = pg.time.Clock()
FPS = 60
ground_scroll = 0
scroll_speed = 4
is_active = True
game_running = False
game_over = False
pipe_gap = 230
pipe_frequency = 1500
first_play = True
last_pipe = pg.time.get_ticks() - pipe_frequency
screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
score = 0
passed_pipe = False
pg.display.set_caption('Flappy Bird', 'Assets/yellowbird-downflap.png')

bg = pg.image.load('Assets/bg.png')
ground_img = pg.image.load('Assets/ground.png')
button_img = pg.image.load('Assets/PlayButton.png')
start_screen_img = pg.image.load('Assets/message.png')
font = pg.font.Font('Assets/Grand9K Pixel.ttf', 60)
white_color = (255, 255, 255)
def draw_text(text, font, text_color, x, y):
    img = font.render(text, True, text_color)
    screen.blit(img, (x, y))

def restart_game():
    pipe_group.empty()
    player.rect.x = 50
    player.rect.y = SCREEN_WIDTH // 2
    score = 0
    return 0
class Bird(pg.sprite.Sprite):
    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.images = []
        self.index = 0
        self.counter = 0
        for i in range(1, 4):
            img = pg.image.load(f'Assets/bird{i}.png')
            self.images.append(img)

        self.image = self.images[self.index]
        self.rect = self.image.get_rect()
        self.rect.center = [x, y]
        self.velocity = 0
        self.clicked = False

    def update(self):
        if game_running:
            self.velocity += 0.5
            if self.velocity > 8:
                self.velocity = 8
            if self.rect.bottom < 600:
                self.rect.y += int(self.velocity)
        if not game_over:
            if pg.mouse.get_pressed()[0] == 1 and not self.clicked:
                self.velocity -= 10
                self.clicked = True

            if pg.mouse.get_pressed()[0] == 0:
                self.clicked = False

            self.counter += 1
            flap_cooldown = 5

            if self.counter > flap_cooldown:
                self.counter = 0
                self.index += 1
            if self.index >= len(self.images):
                self.index = 0
            self.image = self.images[self.index]
            self.image = pg.transform.rotate(self.images[self.index], self.velocity * -2)
        else:
            self.image = pg.transform.rotate(self.images[self.index], -90)

class Pipe(pg.sprite.Sprite):
    def __init__(self, x, y, pos):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load('Assets/pipe.png')
        self.rect = self.image.get_rect()
        if pos == 1:
            self.image = pg.transform.flip(self.image, False, True)
            self.rect.bottomleft = [x, y - int(pipe_gap / 2)]
        else:
            self.rect.topleft = [x, y + int(pipe_gap / 2)]
    def update(self):
        self.rect.x -= scroll_speed
        if self.rect.right < 0:
            self.kill()

class Button():
    def __init__(self, x, y, image):
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)

    def draw(self):
        mouse_position = pg.mouse.get_pos()
        is_pressed = False
        if self.rect.collidepoint(mouse_position):
            if pg.mouse.get_pressed()[0] == 1:
                is_pressed = True

        screen.blit(self.image, (self.rect.x, self.rect.y))
        return is_pressed

bird_group = pg.sprite.Group()
pipe_group = pg.sprite.Group()
player = Bird(100, SCREEN_HEIGHT / 2)

bird_group.add(player)

button = Button(SCREEN_WIDTH // 2 - 30, SCREEN_HEIGHT // 2 - 40, button_img)




req = requests.get('https://skopje.pulse.eco/rest/current')
to_json = json.loads(req.text)
rand_idx = random.randint(0, len(to_json))
value = to_json[rand_idx]['value']
if int(value) < 40:
    pipe_gap = 230
else:
    pipe_gap = 150
while is_active:
    clock.tick(FPS)

    screen.blit(bg, (0, 0))

    bird_group.draw(screen)
    bird_group.update()
    pipe_group.draw(screen)
    screen.blit(ground_img, (ground_scroll, 600))

    if len(pipe_group) > 0:
        if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.left and bird_group.sprites()[0].rect.right < pipe_group.sprites()[0].rect.right and passed_pipe == False:
            passed_pipe = True
        if passed_pipe:
            if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.right:
                score += 1
                passed_pipe = False
        print(score)
    draw_text(str(score), font, white_color, int(SCREEN_WIDTH / 2), 40)

    if pg.sprite.groupcollide(bird_group, pipe_group, False, False) or player.rect.top < 0:
        game_over = True

    if player.rect.bottom > 600:
        game_over = True
        game_running = False

    if game_over == False and game_running == True:
        current_time = pg.time.get_ticks()
        if current_time - last_pipe > pipe_frequency:
            random_height = random.randint(-100, 100)
            bottom_pipe = Pipe(SCREEN_WIDTH, int(SCREEN_HEIGHT / 2) + random_height, 1)
            up_pipe = Pipe(SCREEN_WIDTH, int(SCREEN_HEIGHT / 2) + random_height, -1)
            pipe_group.add(bottom_pipe)
            pipe_group.add(up_pipe)
            last_pipe = current_time
        pipe_group.update()
        ground_scroll -= scroll_speed
        if abs(ground_scroll) > 35:
            ground_scroll = 0


    if game_over:
        if button.draw():
            game_over = False
            score = restart_game()



    for event in pg.event.get():
        if event.type == pg.QUIT:
            is_active = False
        if event.type == pg.MOUSEBUTTONDOWN and not game_running and not game_over:
            game_running = True

    pg.display.update()
pg.quit()
