from pyscript.js_modules import bonds
import cookie
from pyscript import document, ffi, window
from scenes import SelectorScene, Game
from res import Layer, Sound



WIDTH = 1280
HEIGHT = 720

ctx_layer1 = Layer.layer1.getContext("2d")
ctx_layer3 = Layer.layer3.getContext("2d")
ctx_layer4 = Layer.layer4.getContext("2d")

#Настройка качества рендеринга
ctx_layer1.imageSmoothingQuality = 'high'
ctx_layer3.imageSmoothingQuality = 'high'
ctx_layer4.imageSmoothingQuality = 'high'

Layer.layer1.width = WIDTH
Layer.layer3.width = WIDTH
Layer.layer4.width = WIDTH

Layer.layer1.height = HEIGHT
Layer.layer3.height = HEIGHT
Layer.layer4.height = HEIGHT

selector: SelectorScene | None = None

def _start_game(saveData):
    global selector
    # масштабирование
    _resize(None)
    # выбор языка
    if bonds.API() == 'yandex':
        if window.ysdk.environment.i18n.lang in ['ru', 'be', 'kk', 'uk', 'uz']:
            cookie.lang = 'ru'
        else:
            cookie.lang = 'en'
        # реклама при старте
        window.ysdk.adv.showFullscreenAdv()
    else:
        cookie.lang = 'ru' if 'ru' in window.navigator.language else 'en'
    # загрузка
    cookie.load(saveData)
    bonds.ready()  # сообщаем яндекс апи что игра загрузилась
    # скрыть индикатор загрузки
    preloader = document.getElementById("preloader")
    content = document.getElementById("content")
    preloader.style.display = "none"
    content.style.display = "block"
    # загрузка сцены
    selector = SelectorScene(WIDTH, HEIGHT)

    # рисуем
    window.requestAnimationFrame(draw)



lastLogicTime = 0
logicStep = 1000 / 40 - 0.2

renderStep = 1000 / 60 - 0.2
lastRenderTime = 0

def _draw(timeStamp):
    global lastLogicTime
    global lastRenderTime
    # ограничение отсутствия
    if timeStamp - lastLogicTime >= logicStep * 10:
        lastLogicTime = timeStamp

    # логика
    if lastLogicTime == 0:
        lastLogicTime = timeStamp
    while timeStamp - lastLogicTime >= logicStep:
        selector.current_scene.update()
        lastLogicTime += logicStep

    # рисуем
    if timeStamp - lastRenderTime >= renderStep:

        lastRenderTime = timeStamp

        ctx_layer1.clearRect(0, 0, WIDTH, HEIGHT)
        ctx_layer3.clearRect(0, 0, WIDTH, HEIGHT)
        ctx_layer4.clearRect(0, 0, WIDTH, HEIGHT)
        selector.current_scene.draw(ctx_layer1, ctx_layer3, ctx_layer4)
        # частицы на отдельном холсте
        if hasattr(selector.current_scene, 'draw_particles'):
            selector.current_scene.draw_particles(ctx_layer3)

    window.requestAnimationFrame(draw)



def get_coord_with_scale(x, y, canvas):
    scale_x = canvas.width / canvas.clientWidth
    scale_y = canvas.height / canvas.clientHeight
    return x * scale_x, y * scale_y


def _on_mouse_down(e):
    selector.current_scene.mouse_down(*get_coord_with_scale(e.offsetX, e.offsetY, Layer.layer1))

def _on_mouse_move(e):
    selector.current_scene.mouse_move(*get_coord_with_scale(e.offsetX, e.offsetY, Layer.layer1))


def _on_mouse_up(e):
    selector.current_scene.mouse_up(*get_coord_with_scale(e.offsetX, e.offsetY, Layer.layer1))

def _on_mouse_out(e):
    on_mouse_up(e)


touch_x = 0
touch_y = 0
def _on_touch_start(e):
    global touch_x
    global touch_y
    rect = Layer.layer4.getBoundingClientRect()
    touch = e.touches.item(0)
    touch_x = touch.clientX - rect.left
    touch_y = touch.clientY - rect.top
    selector.current_scene.mouse_down(*get_coord_with_scale(touch_x, touch_y, Layer.layer1))

def _on_touch_move(e):
    global touch_x
    global touch_y
    rect = Layer.layer4.getBoundingClientRect()
    touch = e.touches.item(0)
    touch_x = touch.clientX - rect.left
    touch_y = touch.clientY - rect.top
    selector.current_scene.mouse_move(*get_coord_with_scale(touch_x, touch_y, Layer.layer1))


def _on_touch_end(e):
    selector.current_scene.mouse_up(*get_coord_with_scale(touch_x, touch_y, Layer.layer1))



def _visibility_change(e): # при сворачивании
    if document.hidden:
        bonds.stop()
        # Вкладка свернута или не активна надо остановить звук
        Sound.crane.pause()
        Sound.crane.currentTime = 0
        Sound.water.pause()
        Sound.water.currentTime = 0
        Sound.click.pause()
        Sound.click.currentTime = 0
    else:
        if type(selector.current_scene) == Game and not selector.current_scene.is_end_level:
            bonds.start()

def _resize(e):
    element = document.getElementById('content')
    if window.innerWidth < window.innerHeight*1.77:
        element.style.width = '100%'
        element.style.height = '56vw'
    else:
        element.style.width = '177vh'
        element.style.height = '100%'


# create_proxy
start_game = ffi.create_proxy(_start_game)
draw = ffi.create_proxy(_draw)

visibility_change = ffi.create_proxy(_visibility_change)
resize = ffi.create_proxy(_resize)
document.addEventListener("visibilitychange", visibility_change)
window.addEventListener("resize", resize)

on_mouse_down = ffi.create_proxy(_on_mouse_down)
on_mouse_move = ffi.create_proxy(_on_mouse_move)
on_mouse_up = ffi.create_proxy(_on_mouse_up)
on_mouse_out = ffi.create_proxy(_on_mouse_out)

on_touch_start = ffi.create_proxy(_on_touch_start)
on_touch_move = ffi.create_proxy(_on_touch_move)
on_touch_end = ffi.create_proxy(_on_touch_end)

Layer.layer4.addEventListener("mousedown", on_mouse_down)
Layer.layer4.addEventListener("mousemove", on_mouse_move)
Layer.layer4.addEventListener("mouseup", on_mouse_up)
Layer.layer4.addEventListener("mouseout", on_mouse_out)

Layer.layer4.addEventListener("touchstart", on_touch_start)
Layer.layer4.addEventListener("touchmove", on_touch_move)
Layer.layer4.addEventListener("touchend", on_touch_end)


# запуск игры
bonds.init(start_game)






