#!/usr/bin/env python

stable_ip='192.168.0.2'


# To get a Py3k-like print function
#from __future__ import print_function

from flask import Flask,request,jsonify

# Load Pillow
from PIL import Image, ImageDraw, ImageFont

# Load the FBInk wrapper module
from _fbink import ffi, lib as FBInk

import time
import requests

from multiprocessing import Process

app = Flask(__name__)

# Let's check which FBInk version we're using...
# NOTE: ffi.string() returns a bytes on Python 3, not a str, hence the extra decode
print("Loaded FBInk {}".format(ffi.string(FBInk.fbink_version()).decode("ascii")))

# Setup the config...
fbink_cfg = ffi.new("FBInkConfig *")
fbink_cfg.is_centered = True
fbink_cfg.is_halfway = True
fbink_cfg.is_verbose = True
fbink_cfg.is_flashing = True


# path to the log file you want to tail
log_file = "/mnt/us/documents/My Clippings.txt"

# open the log file and seek to the end
with open(log_file, "r") as f:
    f.seek(0, 2)  # move the file pointer to the end of the file
    prev_log = f.read()  # read the entire file



 



@app.route("/robprogress/<progressTime>")
def robprogress(progressTime):
    im = Image.new("RGBA", (600, 800),(0, 0, 0, 0))
    draw = ImageDraw.Draw(im)
    progressTime = int(progressTime)

    draw.rounded_rectangle((100, 375, 500, 450), fill='white',outline="black",  width=3, radius=17)

    fbfd = FBInk.fbink_open()
    FBInk.fbink_init(fbfd, fbink_cfg)
    draw = ImageDraw.Draw(im)

    display_fb(im)

    for i in range(progressTime):
        print ("waited {} seconds".format(i))
        printout="Loading {}/{} seconds".format(i,progressTime)
        FBInk.fbink_print(fbfd, printout.encode('ASCII'), fbink_cfg)
        time.sleep(1)

    FBInk.fbink_close(fbfd)
    return("should have worked")






#upload and then set the kindle screen
@app.route('/uploadthen', methods=['POST'])
def uploadthen():
    file = request.files['image']
    im = Image.open(file.stream)

    # Rotate image if necessary
    if im.width > im.height:
        im = im.transpose(Image.ROTATE_270)

    # Resize image
    im.thumbnail((600, 800), Image.ANTIALIAS)

    # Draw on image
    ImageDraw.Draw(im)
    # ...
    
    # Display image
    display_fb(im)

    return "Image uploaded successfully!"





def display_fb(im ):

    # Now, make sure we'll pass raw data in a format FBInk/stb knows how to handle, doing as few conversions as possible.
    # If image is paletted, translate that to actual values, because stb won't know how to deal with paletted raw data...
    if im.mode == "P":
        print("Image is paletted, translating to actual values")
        # NOTE: No mode means "just honor the palette". Usually, that's RGB.
        #       We could also enforce Grayscale (L), but FBInk/stb will take care of that if needed.
        im = im.convert()

    # If image is not grayscale, RGB or RGBA (f.g., might be a CMYK JPEG) convert that to RGBA.
    if im.mode not in ["L", "RGB", "RGBA"]:
        print("Image data is packed in an unsupported mode, converting to RGBA")
        im = im.convert("RGBA")

    # And finally, get that image data as raw packed pixels.
    raw_data = im.tobytes("raw")

    raw_len = len(raw_data)
    print("Raw data buffer length: {}".format(raw_len))

    # Print the image using FBInk
    fbfd = FBInk.fbink_open()
    try:
        FBInk.fbink_init(fbfd, fbink_cfg)
        FBInk.fbink_print_raw_data(fbfd, raw_data, im.width, im.height, raw_len, 0, 0, fbink_cfg)
    finally:
        FBInk.fbink_close(fbfd)
    



#checking for a change in highlights

def record_loop(loop_on):
  while True:
    with open(log_file, "r") as f:
        new_log = f.read()  # read the entire file

    if new_log != prev_log:
        # split the log file into sections based on the separator
        sections = new_log.split("==========\n")
        last_section = sections[-2].strip()  # -2 to skip the final empty section
        last_line = last_section.split('\n')[-1]  # get the last line of the last section
        print(last_line)
    
        # Get the text to send from the request
        text = last_line.encode('utf-8')
    
        # Send the text to the endpoint
        url = 'http://{}:5000/text'.format(stable_ip)
        response = requests.post(url, data=text)
    
        # Return the response from the endpoint
        print ("printed {} and {}".format(last_line,response.text))

        # update the previous log contents to the current contents

    time.sleep(1)  # wait for a second before checking the file again


if __name__ == "__main__":
   #recording_on = Value('b', True)
   #p = Process(target=record_loop, args=(recording_on,))
   p = Process(target=record_loop)
   p.start()  
   app.run(debug=False,host='0.0.0.0')
   p.join()
   

