import pyperclip

from draftsman.blueprintable import Blueprint, BlueprintBook
from draftsman.constants import Direction
from draftsman.entity import ConstantCombinator

# from draftsman.data import items
import draftsman.data.signals
from PIL import Image

blueprint = Blueprint()
blueprint.label = "bad apple"
blueprint.description = "bad apple."
blueprint.version = (1, 0)  # 1.0

frame = Image.open("frame.png")
threshold = 40
signals = list(draftsman.data.signals.raw)[3:]  # skip the three special signals


pixels = frame.load()

# Create the combinator for the single frame
frame_combinator = ConstantCombinator()
frame_combinator.tile_position = (-1, 0)
for x in range(frame.width):
    column_mask = 0
    for y in range(frame.height):
        if pixels[x, y][0] > threshold:
            column_mask |= 1 << y
    frame_combinator.set_signal(index=x, signal=signals[x], count=column_mask)
blueprint.entities.append(frame_combinator)

pyperclip.copy(blueprint.to_string())

# Code for creating the column filters below.

# for x in range(frame.width):
#     blueprint.entities.append(  # this is our y-combinator :^)
#         "arithmetic-combinator",
#         id=f"filter-{x}",
#         tile_position=[x, 2],
#         direction=Direction.NORTH,
#         control_behavior={
#             "arithmetic_conditions": {
#                 "first_signal": signals[x],
#                 "operation": "AND",
#                 "second_signal": {"type": "virtual", "name": "signal-each"},
#                 "output_signal": {"type": "virtual", "name": "signal-each"},
#             }
#         },
#     )


# arithmetic_conditions = {
#     "first_signal": {"type": "fluid", "name": "steam"},
#     "second_signal": {"type": "virtual", "name": "signal-each"},
#     "operation": "AND",
#     "output_signal": {"type": "virtual", "name": "signal-each"},
#     "first_signal_networks": {"red": True, "green": False},
#     "second_signal_networks": {"red": False, "green": True},
# }

# from draftsman.utils import JSON_to_string

# # directly hack in these conditions because this is a new feature and we don't care about the validation bullshit
# d = blueprint.to_dict()
# for entity in d["blueprint"]["entities"]:
#     entity["control_behavior"]["arithmetic_conditions"][
#         "first_signal_networks"
#     ] = {"red": True, "green": False}
#     entity["control_behavior"]["arithmetic_conditions"][
#         "second_signal_networks"
#     ] = {"red": False, "green": True}

# s = JSON_to_string(d)
# pyperclip.copy(str(s))
