#!/usr/bin/env python3

import os
import tkinter as tk
import traceback
from tkinter import messagebox
from tkinter import scrolledtext
from tkinter import simpledialog
import subprocess
import platform

font = "Arial, Microsoft YaHei, Noto Sans"
font_size = 16
os_system = platform.system()
os_user = os.getlogin()
tmp_file = "/tmp/c-ide.c"
full_edit = False

if os_system == "Darwin":
    os_system = "MacOS"
elif os_system == "Windows":
    tmp_file = f"C:/Users/{os_user}/AppData/Local/tmp/c-ide.tmp"

insert = False
tmp_v = ""


def save_file():
    input_path = simpledialog.askstring(title="Save File?", prompt="Path:")
    if input_path is None or input_path == "":
        return
    with open(f"{input_path}", "w", encoding='utf-8') as f:
        f.write(f'{user_input.get()}')


def order(event=None):
    order_input = simpledialog.askstring(title="run-command", prompt="Run this command: ")
    if order_input is None or order_input == "":
        return
    elif order_input == ":wq":
        save_file()
    elif order_input == ":q":
        confirm_exit = messagebox.askokcancel(title="Confirm Exit?", message="Do you want to exit?")
        if confirm_exit:
            root.destroy()
            exit()
        else:
            return
    elif order_input == ":run":
        run_code()
    else:
        try:
            output = subprocess.run(f'{order_input}', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    text=True, check=True)
            messagebox.showinfo(title="from Shell", message=output.stdout)
            return
        except subprocess.CalledProcessError as e:
            messagebox.showerror(title="from Shell", message=e.stderr)
            return


root = tk.Tk()
root.title(f"CIDE | {os_system}")
root.attributes("-fullscreen", False)
root.geometry("1400x1100")
root.config(bg="#FFFFFF")

user_input = tk.StringVar()
user_input.set("")

title_label = tk.Label(root, text=f"CIDE 1.0723 | {os_system}", font=(font, 18), bg="#F3F3F3")
title_label.pack(pady=(10, 20))

model = tk.Label(root, text="--PREVIEW--", font=(font, 12), bg="#F3F3F3")
model.pack(pady=(5, 10))

word_num = tk.Label(root, text=f"0", font=(font, 12), width=10, bg="#F3F3F3")
word_num.pack(pady=(10, 10))

input_text = tk.scrolledtext.ScrolledText(root, wrap=tk.CHAR, width=150, font=(font, font_size), height=70)
input_text.pack(pady=(10, 10), padx=(10, 10))

input_text.insert("1.0", "Click I to edit.")
input_text.config(state="disabled")

def on_insert(event=None):
    global insert
    insert_text = input_text.get("1.0", "end-1c")
    if not insert:
        insert = True
        input_text.config(state="normal")
        model.config(text="--INSERT--")
        if insert_text == "Click I to edit.":
            input_text.delete("1.0", "end")
        else:
            return
    else:
        return


def off_insert(event=None):
    global insert
    if insert:
        insert = False
        input_text.config(state="disabled")
        model.config(text="--PREVIEW--")
    else:
        return


def update_input(event=None):
    content = input_text.get("1.0", "end-1c")
    user_input.set(content)
    word_num.config(text=f"{len(input_text.get("1.0", "end-1c"))}")


def font_size_enlarge(event=None):
    global font_size
    if font_size <= 120:
        font_size = font_size + 1
        input_text.config(font=(font, font_size))
    else:
        return


def font_size_de(event=None):
    global font_size
    if font_size >= 12:
        font_size = font_size - 1
        input_text.config(font=(font, font_size))
    else:
        return


def run_code_tmp():
    global tmp_v
    tmp_v = tmp_file.removesuffix(".c")
    try:
        if os.path.exists(f"{tmp_file}"):
            os.remove(f"{tmp_file}")
        if os.path.exists(f"{tmp_v}"):
            os.remove(f"{tmp_v}")
    except:
        messagebox.showerror(title="Error", message=f"Error info:\n{traceback.format_exc()}")
        return


def run_code(event=None):
    global tmp_v
    content = input_text.get("1.0", "end-1c").strip()

    if not content or content == "Click I to edit.":
        messagebox.showerror(title="Error", message="No code to compile!")
        return

    with open(f"{tmp_file}", "w", encoding='utf-8') as f:
        f.write(content)
    tmp_v = tmp_file.removesuffix(".c")
    output = subprocess.run(["gcc", f"{tmp_file}", "-o", f"{tmp_v}"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    if output.returncode != 0:
        messagebox.showerror(title="Error", message=f"Error info:\n{output.stderr}")
        run_code_tmp()
        return

    run_output = subprocess.run([f"{tmp_v}"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    if run_output.returncode != 0:
        messagebox.showerror(title="Error", message=f"Error info:\n{run_output.stderr}")
        run_code_tmp()
        return

    messagebox.showinfo(title="CIDE-run", message=run_output.stdout)

    run_
