import ipywidgets as widgets
import os

image_path = os.path.abspath('../../data_files/trees.jpg')

with open(image_path, 'rb') as f:
    raw_image = f.read()
ipyimage = widgets.Image(value=raw_image, format='jpg')
ipyimage

"""
Explanation: The Image Mark
Image is a Mark object, used to visualize images in standard format (png, jpg etc...), in a bqplot Figure
It takes as input an ipywidgets Image widget
The ipywidgets Image
End of explanation
"""


from bqplot import LinearScale, Figure, Lines, Axis, Image

# Create the scales for the image coordinates
scales={'x': LinearScale(), 'y': LinearScale()}
# Define the bqplot Image mark
image = Image(image=ipyimage, scales=scales)
# Create the bqplot Figure to display the mark
fig = Figure(title='Trees', marks=[image], padding_x=0, padding_y=0)
fig

"""
Explanation: Displaying the image inside a bqplot Figure
End of explanation
"""


scales = {'x': LinearScale(min=-1, max=2), 'y': LinearScale(min=-0.5, max=2)}
image = Image(image=ipyimage, scales=scales)
lines = Lines(x=[0, 1, 1, 0, 0], y=[0, 0, 1, 1, 0], scales=scales, colors=['red'])
fig = Figure(marks=[image, lines], padding_x=0, padding_y=0, animation_duration=1000)
fig.axes = [Axis(scale=scales['x']), Axis(scale=scales['y'], orientation='vertical')]
fig

"""
Explanation: Mixing with other marks
Image is a mark like any other, so they can be mixed and matched together.
End of explanation
"""


# Full screen
image.x = [-1, 2]
image.y = [-.5, 2]

"""
Explanation: Its traits (attributes) will also respond dynamically to a change from the backend
End of explanation
"""


def print_event(_, target):
    print(target)
    
image.on_element_click(print_event)

"""
Explanation: Interactions
Like other bqplot marks, you can watch for mouse clicks. For the image mark, the position of the click (on the x/y scale set up in the figure) is returned.
End of explanation
"""


import bqplot.pyplot as bqp

bqp.figure()
bqp.imshow(image_path, 'filename')
bqp.show()

"""
Explanation: Pyplot
It may seem verbose to first open the image file, create an ipywidgets Image, then create the scales and so forth.
The pyplot api does all of that for you, via the imshow function.
End of explanation
"""


