# pie_chart_python.py
# September - 2026
# RJM Programming
# Thanks to https://www.w3schools.com/python/default.asp

import os
import matplotlib
import sys

# Set backend to Agg before importing pyplot
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import numpy as np
#import plotly.express as px
from PIL import Image

nums = []
lbls = []
mytitle = ""
sofar = 0
place = ''
midsuff = ''
if len(sys.argv[0].split('/')) > 1:
  fname = sys.argv[0].split(".py")[0].split('/')[-1 + len(sys.argv[0].split(".py")[0].split('/'))];
else:
  fname = sys.argv[0].split(".py")[0];
fname = fname.split("\\")[-1 + len(fname.split("\\"))].replace('_','').replace('_','').replace('_','').replace('_','').replace('_','').replace('_','');
fname = fname.split('_0')[0].split('_1')[0].split('_2')[0].split('_3')[0].split('_4')[0].split('_5')[0].split('_6')[0].split('_7')[0].split('_8')[0].split('_9')[0]
fname = fname.split('0')[0].split('1')[0].split('2')[0].split('3')[0].split('4')[0].split('5')[0].split('6')[0].split('7')[0].split('8')[0].split('9')[0]
if len(sys.argv) > 1:
  place = sys.argv[-1 + len(sys.argv)]

if len(sys.argv) > 2:
  midsuff = sys.argv[-2 + len(sys.argv)].replace(fname,'').replace('.py','')

if len(nums) <= 0:
  while sofar < 100 and sofar >= 0:
     if fname == "piechartpython":
       print(f"Enter your percentage value regarding a pie chart where so far {sofar} has already been allocated.  Can append after a comma a pie chart sector label.")
     elif fname == "columnchartpython":
       print(f"Enter your value regarding a column chart and append after a comma a column chart label on X axis.")
     elif fname == "scatterchartpython":
       print(f"Enter your X axis value regarding a scatter chart and append after a comma a scatter chart value on Y axis.")
     elif fname == "stairschartpython":
       print(f"Enter your value regarding a stairs chart.")
     elif fname == "pseudocolourchartpython" or fname == "pseudocolorchartpython":
       print(f"Enter your value regarding a psedocolour chart.")
     elif fname == "hexbinchartpython":
       print(f"Enter your X axis value regarding a hexbin chart and append after a comma a hexbin chart value on Y axis.")
     elif fname == "stemchartpython":
       print(f"Enter your X axis value regarding a stem chart and append after a comma a stem chart value on Y axis.")
     elif fname == "barchartpython":
       print(f"Enter your value regarding a bar chart and append after a comma a bar chart label on Y axis.")
     anum = input()
     if anum == "":
       sofar = -1
     elif "," in anum:
       x = anum.split(",")
       nums.append(int(x[0]))
       lbls.append(anum.replace(x[0] + ',', ''))
       if fname == "piechartpython":
         sofar += int(x[0])
     else:
       nums.append(int(anum))
       lbls.append('')
       if fname == "piechartpython":
         sofar += int(anum)
  

y = np.array(nums)


if fname == "hexbinchartpython" or fname == "stairschartpython" or fname == "pseudocolourchartpython" or fname == "pseudocolorchartpython":
  plt.style.use('_mpl-gallery-nogrid')
  if fname == "pseudocolourchartpython" or fname == "pseudocolorchartpython":
    X, Y = np.meshgrid(nums, np.linspace(-3, 3, 128))
    Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)

fig, ax = plt.subplots()

if len(mytitle) > 0:
  plt.title(mytitle)

if fname == "scatterchartpython":
  ax.scatter(nums, lbls)
elif fname == "stemchartpython":
  ax.stem(nums, lbls)
elif fname == "hexbinchartpython":
  ax.hexbin(nums, lbls)
elif fname == "stairschartpython":
  ax.stairs(nums)
elif fname == "pseudocolourchartpython" or fname == "pseudocolorchartpython":
  ax.pcolormesh(X, Y, Z, vmin=-0.5, vmax=1.0)
elif fname == "columnchartpython":
  ax.bar(lbls, nums)
elif fname == "barchartpython":
  ax.barh(lbls, nums)
elif len(lbls) < len(nums) and fname == "piechartpython":
  ax.pie(y, autopct="%1.1f%%")
elif fname == "piechartpython":
  ax.pie(y, labels=lbls)

fig.savefig(place + "plot" + midsuff + ".png", bbox_inches="tight")


# 1. Load the image
img = mpimg.imread(place + 'plot' + midsuff + '.png')

# 2. Process or manipulate the image (Optional)
# For example, let's look at the shape or apply changes
#print(f"Image shape: {img.shape}")

# 3. Create the plot without displaying it
plt.imshow(img)
plt.axis('off')  # Hide axis lines and labels

# 4. Save the result to a file instead of showing it
plt.savefig(place + 'output_image' + midsuff + '.png', bbox_inches='tight', pad_inches=0)
plt.close()


# Open the PNG image file
with Image.open(place + "plot" + midsuff + ".png") as img:
    # Display the image using your system's default viewer
    img.show()
    
    # Optional: Load the data into memory so you can safely close the file
    img.load() 


exit()


  
