import type { HttpContext } from '@adonisjs/core/http';
import { StatusCodes } from 'http-status-codes';
// import * as fs from 'fs';
// import * as path from 'path';

const prefixes = ['von', 'van'];

// node ace make:controller Author
export default class AvatarController {
    public async generateAvatar({ request, response }: HttpContext) {
        try {
            const { name, background, textColor, size } = request.only(['name', 'background', 'textColor', 'size']);

            // Generate initials
            // const initials = name
            //     .split(' ')
            //     .map((part) => part.charAt(0).toUpperCase())
            //     .join('');
            const initials = this.getInitials(name);

            // Define SVG content with dynamic values for initials, background color, text color, and size
            const svgContent = `
            <svg width="${size || 50}" height="${size || 50}" xmlns="http://www.w3.org/2000/svg">
              <rect width="100%" height="100%" fill="#${background || '7F9CF5'}"/>
              <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-weight="bold" font-family="Arial, sans-serif" font-size="${
                  (size / 100) * 40 || 25
              }" fill="#${textColor || 'ffffff'}">${initials}</text>
            </svg>
          `;

            // Set response headers for SVG content
            response.header('Content-type', 'image/svg+xml');
            response.header('Cache-Control', 'no-cache');
            response.header('Pragma', 'no-cache');
            response.header('Expires', '0');

            return response.send(svgContent);
        } catch (error) {
            return response.status(StatusCodes.OK).json({ error: error.message });
        }
    }

    private getInitials(name: string) {
        const parts = name.split(' ');
        let initials = '';

        if (parts.length >= 2) {
            const firstName = parts[0];
            const lastName = parts[parts.length - 1];

            const firstInitial = firstName.charAt(0).toUpperCase();
            const lastInitial = lastName.charAt(0).toUpperCase();

            if (prefixes.includes(lastName.toLowerCase()) && lastName === lastName.toUpperCase()) {
                initials = firstInitial + lastName.charAt(1).toUpperCase();
            } else {
                initials = firstInitial + lastInitial;
            }
        } else if (parts.length === 1) {
            initials = parts[0].substring(0, 2).toUpperCase();
        }

        return initials;
    }
}
