#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Проект "Построение графика", подзадача pygame 1-1
"Резиновые линии":
  левая кнопка мыши -- начать/закончить  рисование "резиновой" линии
  перемещение мыши -- рисовать
  правая кнопка мыши -- не рисовать
  "Q", закрытие окна -- выйти
  пробел -- включить/выключить вывод всех событий на текстовый экран
'''

from math import *
import sys

import pygame
pygame.init()

def Draw(screen, pen, width, center, pos, figure):
	if figure == "Line":
		pygame.draw.line(screen, pen, center, pos, width)
	elif figure == "Rect":
		pygame.draw.rect(screen, pen, (center, (pos[0]-center[0],pos[1]-center[1])), width)

W, H = 640, 480
pen,width=(10,100,200),2
screen=pygame.display.set_mode((W,H))
States=("Draw", "Input", "Base")
Figures={"O":"Circle", "L":"Line", "R":"Rect"}
Inputs={"W":"Width", "C":"Color", "S":"Save", "E":"Edit"}
Center=(0,0)
Copy=None

State, Stage, Action = "Base", 1, "Line"
while True:
  pygame.display.flip()
  event = pygame.event.wait()
  # Выход по закрытию окна и нажатии "q"
  if event.type == pygame.QUIT: sys.exit()
  if State == "Base":	# основное состояние
	if event.type == pygame.KEYDOWN:
		if event.unicode in "LlRr":
			State,Stage,Action = "Draw", 1, Figures[event.unicode.upper()]
			Copy = screen.copy()
		elif event.unicode in "Ww":
			width=input("Введите ширину линии: ")
		elif event.unicode in "Cc":
			pen=input("Введите цвет линии: ")		
		elif event.unicode in "Qq":
			sys.exit()
  elif State == "Draw":	# рисование фигуры
	if event.type == pygame.MOUSEMOTION:
		if Stage == 2:
			screen.blit(Copy, (0,0))	# восстанавливаем 
			Draw(screen, pen, width, Center, event.pos, Action)
	elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
		if Stage == 1:		# первое нажатие
			Stage = 2
			Center = event.pos
			Copy = screen.copy()	# состояние экрана без нарисованной линии
		elif Stage == 2:	# ВТОРОЕ НАЖАТИЕ
			Stage = 1
	elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
		if Stage == 2:
			screen.blit(Copy, (0,0))	# восстанавливаем 
			Stage = 1
	elif event.type == pygame.KEYDOWN and event.key == 27:
		screen.blit(Copy, (0,0))
		State = "Base"
