#!/bin/bash

# Colors and styles
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
BOLD='\033[1m'
UNDERLINE='\033[4m'
ITALIC='\033[3m'
NC='\033[0m' # No Color

# ASCII art title
function print_logo() {
    cat << "EOF"


   $$$$$\ $$$$$$$\   $$$$$$\  
   \__$$ |$$  __$$\ $$  __$$\ 
      $$ |$$ |  $$ |$$ /  \__|
      $$ |$$$$$$$  |$$ |      
$$\   $$ |$$  ____/ $$ |      
$$ |  $$ |$$ |      $$ |  $$\ 
\$$$$$$  |$$ |      \$$$$$$  |
 \______/ \__|       \______/ 
                              
                            
EOF
    echo -e "\n${BLUE}Device Registration System${NC}\n"
}

print_logo

# Function to get MAC address of the default network interface
# function get_mac_address() {
#     echo -e "${BLUE}Auto-detecting MAC Address...${NC}"
#     INTERFACE=$(ip route | awk '/default/ {print $5; exit}')
    
#     if [[ -n "$INTERFACE" ]]; then
#         MAC=$(cat /sys/class/net/$INTERFACE/address)
#         echo -e "${GREEN}✓ Detected MAC Address: ${BOLD}$MAC${NC}"
#         check_device_status "$MAC"
#     else
#         echo -e "${RED}✗ No active network interface found!${NC}"
#         exit 1
#     fi
# }

function get_mac_address() {
    echo -e "${BLUE}Auto-detecting MAC Addresses...${NC}"
    
    MACS=$(ip link show | awk '/ether/ {print $2}' | grep -v '00:00:00:00:00:00' | paste -sd '_')

    if [[ -n "$MACS" ]]; then
        echo -e "${GREEN}✓ Detected MAC Addresses: ${BOLD}$MACS${NC}"
        check_device_status "$MACS"
    else
        echo -e "${RED}✗ No active network interfaces found!${NC}"
        exit 1
    fi
}


# Function for manual input
function manual_input() {
    echo -e "\n${BLUE}Please enter MAC Address${NC}"
    echo -e "${CYAN}(You can type manually or use a barcode scanner)${NC}"
    read -p "MAC Address: " MAC
    MAC=${MAC:-""}
    echo -e "${NC}"
    
    if [[ -n "$MAC" ]]; then
        check_device_status "$MAC"
    else
        echo -e "${RED}✗ MAC Address cannot be empty!${NC}"
        exit 1
    fi
}

# Function to check device status using the API
function check_device_status() {
    local MAC_ADDRESS="$1"
    
    # Show loading animation
    echo -n "Checking device status... "
    for i in {1..10}; do
        echo -n "."
        sleep 0.1
    done
    echo
    
    API_URL="http://192.168.0.2:3000/check-status?mac=$MAC_ADDRESS"
    RESPONSE=$(curl -s "$API_URL")
    
    if [[ -z "$RESPONSE" ]]; then
        echo -e "${RED}✗ No response from server. Check if the API is running.${NC}"
        exit 1
    fi
    
    # Check status
    STATUS=$(echo "$RESPONSE" | jq -r '.status')
    
    if [[ "$STATUS" == "registered" ]]; then
        SERIAL_NUMBER=$(echo "$RESPONSE" | jq -r '.serialNumber')
        echo -e "${GREEN}✓ Device is already registered.${NC}"
        echo -e "${YELLOW}Serial Number: ${BOLD}$SERIAL_NUMBER${NC}"
    elif [[ "$STATUS" == "new" ]]; then
        echo -e "${GREEN}✓ Device is new. Proceeding to registration.${NC}"
        register_device "$MAC_ADDRESS"
    else
        echo -e "${RED}✗ Unknown status: $STATUS${NC}"
    fi
}

# Function to register the device
function register_device() {
    local MAC_ADDRESS="$1"
    
    # Select variant
    echo -e "${BLUE}Select variant:${NC}"
    echo -e "1. ${GREEN}Pro${NC}"
    echo -e "2. ${YELLOW}Starter${NC}"
    read -p "Enter your choice (1/2): " VARIANT_SELECTION
    
    if [[ "$VARIANT_SELECTION" == "1" ]]; then
        VARIANT="Pro"
    elif [[ "$VARIANT_SELECTION" == "2" ]]; then
        VARIANT="Starter"
    else
        echo -e "${RED}✗ Invalid variant choice. Exiting.${NC}"
        exit 1
    fi
    
    # Get OS information
    OS_NAME=$(grep "^NAME=" /etc/os-release | cut -d= -f2 | tr -d '"')
    
    # Optional customer information
    read -p "Production Number (optional): " PRODUCTION_NUMBER
    read -p "Customer Name (optional): " CUSTOMER_NAME
    read -p "Customer Number (optional): " CUSTOMER_NUMBER
    read -p "Customer Address (optional): " CUSTOMER_ADDRESS
    
    # Show registration details
    echo -e "\n${UNDERLINE}Registration Details:${NC}"
    echo -e "${BOLD}MAC Address: ${GREEN}$MAC_ADDRESS${NC}"
    echo -e "${BOLD}OS: ${CYAN}$OS_NAME${NC}"
    echo -e "${BOLD}Variant: ${YELLOW}$VARIANT${NC}"
    if [[ -n "$PRODUCTION_NUMBER" ]]; then
        echo -e "${BOLD}Production Number: ${MAGENTA}$PRODUCTION_NUMBER${NC}"
    fi
    if [[ -n "$CUSTOMER_NAME" ]]; then
        echo -e "${BOLD}Customer Name: ${MAGENTA}$CUSTOMER_NAME${NC}"
    fi
    if [[ -n "$CUSTOMER_ADDRESS" ]]; then
        echo -e "${BOLD}Customer Address: ${MAGENTA}$CUSTOMER_ADDRESS${NC}"
    fi
    if [[ -n "$CUSTOMER_NUMBER" ]]; then
        echo -e "${BOLD}Phone Number: ${MAGENTA}$CUSTOMER_NUMBER${NC}"
    fi
    
    # Proceed with registration
    echo -e "\n${BLUE}Registering device...${NC}"
    
    # Prepare JSON body
    JSON_BODY=$(jq -n \
        --arg variant "$VARIANT" \
        --arg mac "$MAC_ADDRESS" \
        --arg os "$OS_NAME" \
        --arg status "registered" \
        --arg productionNumber "$PRODUCTION_NUMBER" \
        --arg customerName "$CUSTOMER_NAME" \
        --arg customerAddress "$CUSTOMER_ADDRESS" \
        --arg customerNumber "$CUSTOMER_NUMBER" \
        '{
            Verient: $variant,
            mac: $mac,
            os: $os,
            status: $status,
            productionNumber: $productionNumber,
            customerName: $customerName,
            customerAddress: $customerAddress,
            customerNumber: $customerNumber
        }')
    
    # Send registration request
    REGISTER_URL="http://192.168.0.2:3000/upload"
    REGISTER_RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" -d "$JSON_BODY" "$REGISTER_URL")
    
    if [[ -n "$REGISTER_RESPONSE" ]]; then
        echo -e "\n${GREEN}✓ Device successfully registered!${NC}"
        echo -e "\n${BLUE}Response:${NC}"
        echo -e "${CYAN}"
        echo "$REGISTER_RESPONSE"
    else
        echo -e "\n${RED}✗ Registration failed. No response from server.${NC}"
    fi
}

# Main menu
function show_menu() {
    echo -e "\n${BLUE}Please choose an option:${NC}"
    echo -e "1. ${CYAN}Input MAC Address Manually${NC}"
    echo -e "2. ${GREEN}Auto-detect MAC Address${NC}"
    echo -e "${BLUE}Enter your choice: [1/2]${NC}"
    read -p "" CHOICE
    echo -e "${NC}"
    
    case $CHOICE in
        1) manual_input ;;
        2) get_mac_address ;;
        *) echo -e "${RED}✗ Invalid option. Please select 1 or 2.${NC}"; exit 1 ;;
    esac
}

# Main execution
show_menu
