import datetime
from flask import Blueprint, request, jsonify, send_from_directory
import sqlite3

config_label = Blueprint('label', __name__)
# Connect to database (creates a new one if it doesn’t exist)
conn = sqlite3.connect("my_database.db")
# Create a cursor object to execute SQL commands
cursor = conn.cursor()

# Connect to database
def get_db_connection():
    conn = sqlite3.connect("my_database.db")
    conn.row_factory = sqlite3.Row  # Enables dictionary-like access to rows
    return conn

# Create table (only call once at startup)
def create_table():
    conn = get_db_connection()
    cursor = conn.cursor()

    # Check if the table exists
    cursor.execute("""
        SELECT name FROM sqlite_master WHERE type='table' AND name='labels'
    """)
    table_exists = cursor.fetchone()

    if not table_exists:
        # Create table if it doesn't exist
        cursor.execute("""
            CREATE TABLE labels (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                code INTEGER NOT NULL,
                status TEXT DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        
        # Insert default values
        default_values = [
            ("logo.cisco", 0),
            ("barcode.SN", 1)
        ]
        cursor.executemany("INSERT INTO labels (name, code) VALUES (?, ?)", default_values)
        
        print("Table created and default values inserted.")
    else:
        print("Table already exists.")

    conn.commit()
    conn.close()

# Call create_table() when the script runs
create_table()

# Route to add a new label
@config_label.route('/label/add', methods=['POST'])
def add_label():
    data = request.get_json()  # Get JSON data from request
    name = data.get("name")

    if not name:
        return jsonify({"error": "Name is required"}), 400

    conn = get_db_connection()
    cursor = conn.cursor()

    # Get the last code value
    cursor.execute("SELECT MAX(code) FROM labels")
    last_code = cursor.fetchone()[0]
    new_code = (last_code + 1) if last_code is not None else 1  # Start from 1 if table is empty

    # Insert new label
    cursor.execute(
        "INSERT INTO labels (name, code) VALUES (?, ?)", 
        (name, new_code)
    )

    conn.commit()
    conn.close()

    return jsonify({"message": "Label added successfully", "name": name, "code": new_code, "success" : True}), 201

# Route to update a label
@config_label.route('/label/update', methods=['POST'])
def update_label():
    data = request.get_json()
    name = data.get("name")
    label_id = data.get("id")

    if not name or not label_id:
        return jsonify({"error": "Name and id are required"}), 400

    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute(
        "UPDATE labels SET name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", 
        (name, label_id)
    )
    
    conn.commit()
    conn.close()

    return jsonify({"message": "Label updated successfully", "success" : True}), 200

@config_label.route('/labels', methods=['GET'])
def get_labels():
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM labels WHERE status = 'active'")
    labels = cursor.fetchall()
    
    conn.close()

    # Convert rows to list of dictionaries
    label_list = [dict(row) for row in labels]

    return jsonify(label_list), 200

# Route to delete a label
@config_label.route('/delete/<int:label_id>', methods=['GET'])
def delete_label(label_id):
    if not label_id is None:
        return jsonify({"error": "ID label are required"}), 400

    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute(
        "UPDATE labels SET status = 'delete' WHERE id = ?", 
        (label_id)
    )
    
    conn.commit()
    conn.close()

    return jsonify({"message": "Label delete successfully"}), 200