import tkinter as tk
import time, math, noise
from PIL import Image, ImageDraw, ImageTk

class Graph(tk.Canvas):
  def __init__(self, root, **kwargs):
    self.root = root
    tk.Canvas.__init__(self, root, **kwargs)
    self.height = self.winfo_reqheight()
    self.width = self.winfo_reqwidth()
    self.coord = [(10, 50), (20, 50), (100, 100)]
    
    self.drawBackground()
    self.canvas = self.bg.copy()
    self.image = self.create_image(0, 0, image=None, anchor='nw')

    self.bind("<Configure>", self.on_resize)
    self.n = 0

  def drawBackground(self):
    self.bg = Image.new('RGB', (self.width, self.height), (0,20,0))
    draw = ImageDraw.Draw(self.bg)
    draw.line([(0, self.height/2), (self.width, self.height/2)], (0,127,127), 1)
    draw.line([(self.width/2, 0), (self.width/2, self.height)], (0,127,127), 1)


  def on_resize(self,event):
    # determine the ratio of old width/height to new width/height
    self.width = max(400, event.width-4)
    self.height = max(400, event.height-4)
    # resize the canvas 
    self.config(width=self.width, height=self.height)
    self.canvas = self.canvas.resize((self.width, self.height))
    self.drawBackground()
    self.canvas = Image.blend(self.canvas, self.bg, 0.1)

  def update(self):
    self.coord = [self.coord[-1]]
    for i in range(30):
      self.coord.append(((noise.pnoise1(self.n)+1)*self.width/2, (noise.pnoise1(self.n*1.3+3)+1)*self.height/2))

      self.n += 0.001

    self.canvas = Image.blend(self.canvas, self.bg, 1/250)
    draw = ImageDraw.Draw(self.canvas)
    draw.line(self.coord, fill=(100, 255, 100, 255), width=int(self.height/100), joint='curve')

    self.photo = ImageTk.PhotoImage(self.canvas)
    self.itemconfig(self.image, image=self.photo)
