from tkinter import *
from tkinter import messagebox, filedialog
from datetime import datetime
import os
import sys
from  openpyxl import load_workbook

# GUI for user input
window = Tk()
window.title("議事録作成")
window.geometry("800x630")  # Initial window size
window.resizable(False, False)  # Disable resizing of the window

# Main layout: Frames
main_frame = Frame(window)
main_frame.pack(fill="both", expand=True)

# Scrollable area setup
canvas = Canvas(main_frame)
scroll_frame = Frame(canvas)
scrollbar = Scrollbar(main_frame, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scrollbar.set)

scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((0, 0), window=scroll_frame, anchor="nw")

# Configure scrolling behavior
def on_configure(event):
    canvas.configure(scrollregion=canvas.bbox("all"))
    # スライダーを常に下に位置させる
    canvas.yview_moveto(1.0)

scroll_frame.bind("<Configure>", on_configure)

# Input fields and labels
labels = ["打合日時", "打合社名", "議題", "面会者", "同行者", "議事1", "議事2", "議事3", "宿題(AI)", "その他"]
entries = {}

# Define the label-specific heights
fixed_heights = {
    "面会者": 3, "同行者": 3, "宿題(AI)": 3, "その他": 3,
    "議事1": 5, "議事2": 5, "議事3": 5,
}

# Function to dynamically adjust text height without resetting lines
def adjust_text_height(event, text_widget):
    current_lines = int(text_widget.index('end-1c').split('.')[0])  # 現在の行数を取得
    visible_lines = int(text_widget['height'])  # 現在の表示行数
    if current_lines > visible_lines:  # 行数が表示行数を超えた場合
        text_widget.configure(height=current_lines)  # 高さを更新

# Function to move focus on Tab key
def focus_next(event, idx):
    event.widget.tk_focusNext().focus()
    return "break"

for i, label in enumerate(labels):
    Label(scroll_frame, text=label, anchor="e", width=15).grid(row=i, column=0, padx=(0, 15), pady=5, sticky="e")
    # Set height based on fixed_heights or default to 1
    text_height = fixed_heights.get(label, 1)
    text_widget = Text(scroll_frame, height=text_height, wrap="word")
    text_widget.grid(row=i, column=1, padx=(5, 5), pady=5, sticky="ew")
    entries[label] = text_widget

    # Enable tab navigation
    text_widget.bind("<Tab>", lambda event, idx=i: focus_next(event, idx))

    # Dynamic height adjustment on key release
    text_widget.bind("<KeyRelease>", lambda event, widget=text_widget: adjust_text_height(event, widget))

Button(scroll_frame, text="日付変換", command=lambda: convert_date(entries["打合日時"])).grid(
    row=0, column=2, padx=(0, 50), pady=5, sticky="w"
)

# 日付変換の関数
def convert_date(entry):
    current_year = datetime.now().year
    month_day = entry.get("1.0", END).strip()
    if len(month_day) != 4 or not month_day.isdigit():
        messagebox.showwarning("入力エラー", "日付は4桁（MMDD）で入力してください。")
        return
    month, day = int(month_day[:2]), int(month_day[2:])
    if not (1 <= month <= 12):
        messagebox.showwarning("入力エラー", "月は1～12の範囲で入力してください。")
        return
    if not (1 <= day <= 31):
        messagebox.showwarning("入力エラー", "日は1～31の範囲で入力してください。")
        return
    date = f"{current_year}年{month}月{day}日"
    entry.delete("1.0", END)
    entry.insert(END, date)

# Function to get resource path
def resource_path(relative_path):
    """EXE化したときに正しいパスを取得するための関数"""
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

# Function to save data to Excel
def save_to_excel():
    try:
        data = {label: entry.get("1.0", END).strip() for label, entry in entries.items()}
        template_path = r"C:\Users\shige\OneDrive\デスクトップ\Python\自作プログラム\meeting_template1.xlsx"
        wb = load_workbook(template_path)
        ws = wb.active

        ws['A1'], ws['B1'] = "打合日時", data["打合日時"]
        ws['A2'], ws['B2'] = "打合社名", data["打合社名"]
        ws['A3'], ws['B3'] = "議題", data["議題"]
        ws['A4'], ws['B4'] = "面会者", data["面会者"]
        ws['A5'], ws['B5'] = "同行者", data["同行者"]
        ws['A7'], ws['B7'] = "議事1", data["議事1"]
        ws['A8'], ws['B8'] = "議事2", data["議事2"]
        ws['A9'], ws['B9'] = "議事3", data["議事3"]
        ws['A11'], ws['B11'] = "宿題(AI)", data["宿題(AI)"]
        ws['A13'], ws['B13'] = "その他", data["その他"]

        filename = filedialog.asksaveasfilename(
            defaultextension=".xlsx",
            filetypes=[("Excelファイル", "*.xlsx")],
            initialfile=f"{data['打合社名']}_{data['議題']}_{datetime.now().strftime('%y%m%d')}.xlsx",
            title="保存場所を選択してください"
        )
        if filename:
            wb.save(filename)
            messagebox.showinfo("保存完了", f"議事録が保存されました: {filename}")
        else:
            messagebox.showinfo("キャンセル", "保存がキャンセルされました。")
    except Exception as e:
        messagebox.showerror("エラー", f"保存中にエラーが発生しました: {e}")

# Fixed bottom frame for the save button
bottom_frame = Frame(window)
bottom_frame.pack(fill="x", side="bottom")

Button(
    bottom_frame,
    text="保存",
    command=save_to_excel,
    font=("Arial", 14, "bold"),
    bg="#4CAF50",
    fg="white",
    padx=20,
    pady=10
).pack(pady=10)

window.mainloop()


