import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tkinter import Tk
from tkinter.filedialog import askdirectory
import binascii

print(f"TensorFlow version = {tf.__version__}\n")

# Set a fixed random seed value for reproducibility
SEED = 1337
np.random.seed(SEED)
tf.random.set_seed(SEED)

# Display file dialog to select a folder
root = Tk()
root.withdraw()  # Hide the Tkinter window
folder_path = askdirectory(title="Select Folder")
root.destroy()  # Close the Tkinter window

# List of gestures with available data
GESTURES = []

# Get all CSV files in the selected folder and add to GESTURES
for filename in os.listdir(folder_path):
    if filename.endswith(".csv"):
        GESTURES.append(os.path.splitext(filename)[0])

SAMPLES_PER_GESTURE = 119
NUM_GESTURES = len(GESTURES)

# Create a one-hot encoded matrix for the output
ONE_HOT_ENCODED_GESTURES = np.eye(NUM_GESTURES)

inputs = []
outputs = []

# Define expected columns
expected_columns = ['aX', 'aY', 'aZ', 'gX', 'gY', 'gZ']

# Read each CSV file and populate inputs and outputs
for gesture_index, gesture in enumerate(GESTURES):
    print(f"Processing index {gesture_index} for gesture '{gesture}'.")

    output = ONE_HOT_ENCODED_GESTURES[gesture_index]

    df = pd.read_csv(os.path.join(folder_path, gesture + ".csv"))

    # Check if the expected columns are in the dataframe
    if not all(column in df.columns for column in expected_columns):
        print(f"Error: One or more expected columns are missing in {gesture}.csv")
        continue

    # Calculate the number of gesture recordings in the file
    num_recordings = int(df.shape[0] / SAMPLES_PER_GESTURE)
    print(f"\tThere are {num_recordings} recordings of the {gesture} gesture.")

    for i in range(num_recordings):
        tensor = []
        for j in range(SAMPLES_PER_GESTURE):
            index = i * SAMPLES_PER_GESTURE + j
            # Normalize the input data
            tensor.extend([
                (df['aX'][index] + 4) / 8,
                (df['aY'][index] + 4) / 8,
                (df['aZ'][index] + 4) / 8,
                (df['gX'][index] + 2000) / 4000,
                (df['gY'][index] + 2000) / 4000,
                (df['gZ'][index] + 2000) / 4000
            ])
        inputs.append(tensor)
        outputs.append(output)

# Convert lists to numpy arrays
inputs = np.array(inputs)
outputs = np.array(outputs)

print("Data set parsing and preparation complete.")

# Randomize the order of the inputs
num_inputs = len(inputs)
randomize = np.arange(num_inputs)
np.random.shuffle(randomize)
inputs = inputs[randomize]
outputs = outputs[randomize]

# Split the data into training, testing, and validation sets
TRAIN_SPLIT = int(0.6 * num_inputs)
TEST_SPLIT = int(0.2 * num_inputs + TRAIN_SPLIT)

inputs_train, inputs_test, inputs_validate = np.split(inputs, [TRAIN_SPLIT, TEST_SPLIT])
outputs_train, outputs_test, outputs_validate = np.split(outputs, [TRAIN_SPLIT, TEST_SPLIT])

print("Data set randomization and splitting complete.")

# Build and train the model using Input object
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(SAMPLES_PER_GESTURE * 6,)),
    tf.keras.layers.Dense(50, activation='relu'),
    tf.keras.layers.Dense(15, activation='relu'),
    tf.keras.layers.Dense(NUM_GESTURES, activation='softmax')
])
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])

history = model.fit(inputs_train, outputs_train, epochs=600, batch_size=1, validation_data=(inputs_validate, outputs_validate))

# 関数をラップする
@tf.function
def model_predict(inputs):
    return model(inputs)

# TensorFlow Lite形式に変換
converter = tf.lite.TFLiteConverter.from_concrete_functions([model_predict.get_concrete_function(tf.TensorSpec([None, SAMPLES_PER_GESTURE * 6], tf.float32))])
converter.experimental_new_converter = True
converter.target_spec.supported_ops = [
    tf.lite.OpsSet.TFLITE_BUILTINS,
    tf.lite.OpsSet.SELECT_TF_OPS
]
try:
    tflite_model = converter.convert()
    print("Model successfully converted to TensorFlow Lite format.")
    # モデルを保存
    with open("gesture_model.tflite", "wb") as f:
        f.write(tflite_model)
    print("Model saved to disk successfully.")
except Exception as e:
    print("Error converting model to TensorFlow Lite format:", e)

# TensorFlow Liteモデルをバイナリ形式で読み込む
with open("gesture_model.tflite", "rb") as f:
    tflite_model = f.read()

# バイナリデータをC言語の配列形式に変換
hex_data = binascii.hexlify(tflite_model).decode('utf-8')
hex_array = [hex_data[i:i+2] for i in range(0, len(hex_data), 2)]
formatted_hex_array = ", ".join("0x" + hex_array[i] for i in range(len(hex_array)))

# ヘッダーファイルを生成
header_content = f"const unsigned char model[] = {{\n{formatted_hex_array}\n}};"

with open("model.h", "w") as f:
    f.write(header_content)

# ファイルサイズを表示
model_h_size = os.path.getsize("model.h")
print(f"Header file, model.h, is {model_h_size:,} bytes.")
