import ErrorHandler from './errorHandler.js';
import Logger from './logger.js';
import FontLoader from './fontLoader.js';

// 图片生成器核心类
class ImageGenerator {
  constructor() {
    this.canvas = document.createElement('canvas');
    this.ctx = this.canvas.getContext('2d');
    this.canvas.width = 800;
    this.canvas.height = 600;
    this.template = 'simple'; // 默认模板
    
    // 调整边距配置，增加上下边距
    this.padding = {
      top: 100,      // 减小上边距
      right: 100,
      bottom: 100,   // 减小下边距
      left: 100
    };
    
    // 添加样式配置
    this.styles = {
      fontSize: 28,
      textColor: '#2c3e50',
      backgroundColor: '#ffffff'
    };
  }

  setText(text) {
    this.text = text;
  }

  setTemplate(template) {
    this.template = template;
  }

  setFontSize(size) {
    this.styles.fontSize = parseInt(size);
  }

  setTextColor(color) {
    this.styles.textColor = color;
  }

  setBackgroundColor(color) {
    this.styles.backgroundColor = color;
  }

  async render() {
    switch (this.template) {
      case 'simple':
        await this.renderSimple();
        break;
      case 'gradient':
        await this.renderGradient();
        break;
      case 'movie':
        await this.renderMovie();
        break;
      case 'calligraphy':
        await this.renderCalligraphy();
        break;
      case 'social':
        await this.renderSocial();
        break;
      default:
        await this.renderSimple();
    }
  }

  async renderSimple() {
    // 清空画布
    this.ctx.fillStyle = this.styles.backgroundColor;
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 添加柔和的背景渐变
    const bgGradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height);
    bgGradient.addColorStop(0, this.styles.backgroundColor);
    bgGradient.addColorStop(1, this.styles.backgroundColor);
    this.ctx.fillStyle = bgGradient;
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 添加装饰性边框
    this.ctx.strokeStyle = '#e9ecef';
    this.ctx.lineWidth = 2;
    this.ctx.strokeRect(
      this.padding.left / 2,
      this.padding.top / 2,
      this.canvas.width - this.padding.left,
      this.canvas.height - this.padding.top
    );
    
    // 设置文本样式
    this.ctx.fillStyle = this.styles.textColor;
    this.ctx.font = `${this.styles.fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    
    // 计算可用宽度（考虑边距）
    const availableWidth = this.canvas.width - (this.padding.left + this.padding.right);
    
    // 绘制文本
    const lines = this.wrapText(this.text, availableWidth);
    const lineHeight = 36;
    const totalHeight = lines.length * lineHeight;
    
    // 调整文本起始位置，确保文本居中且不超出边距
    const startY = Math.max(
      this.padding.top,
      Math.min(
        (this.canvas.height - totalHeight) / 2,
        this.canvas.height - totalHeight - this.padding.bottom
      )
    );
    
    // 添加优雅的引号装饰
    this.ctx.font = '80px Georgia, serif';
    this.ctx.fillStyle = 'rgba(44, 62, 80, 0.1)';
    this.ctx.fillText('"', this.padding.left, this.padding.top + 40);
    this.ctx.fillText('"', this.canvas.width - this.padding.right, this.canvas.height - this.padding.bottom - 40);
    
    // 绘制主文本
    this.ctx.font = `${this.styles.fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
    this.ctx.fillStyle = this.styles.textColor;
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        this.canvas.width / 2,
        startY + index * lineHeight
      );
    });
  }

  async renderGradient() {
    // 创建更丰富的渐变背景
    const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, this.canvas.height);
    gradient.addColorStop(0, '#4facfe');
    gradient.addColorStop(1, '#00f2fe');
    
    // 填充背景
    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 添加纹理效果
    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.05)';
    for (let i = 0; i < this.canvas.height; i += 4) {
      this.ctx.fillRect(0, i, this.canvas.width, 2);
    }
    
    // 设置文本样式
    this.ctx.fillStyle = '#ffffff';
    this.ctx.font = `${this.styles.fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    
    // 计算可用宽度（考虑边距）
    const availableWidth = this.canvas.width - (this.padding.left + this.padding.right);
    
    // 绘制文本
    const lines = this.wrapText(this.text, availableWidth);
    const lineHeight = 36;
    const totalHeight = lines.length * lineHeight;
    
    // 调整文本起始位置，确保文本居中且不超出边距
    const startY = Math.max(
      this.padding.top,
      Math.min(
        (this.canvas.height - totalHeight) / 2,
        this.canvas.height - totalHeight - this.padding.bottom
      )
    );
    
    // 添加更柔和的文本阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
    this.ctx.shadowBlur = 8;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;
    
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        this.canvas.width / 2,
        startY + index * lineHeight
      );
    });
    
    // 重置阴影
    this.ctx.shadowColor = 'transparent';
  }

  async renderMovie() {
    // 黑色背景
    this.ctx.fillStyle = '#000000';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 设置文本样式
    this.ctx.fillStyle = '#ffffff';
    this.ctx.font = `${this.styles.fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    
    // 计算可用宽度
    const availableWidth = this.canvas.width - (this.padding.left + this.padding.right);
    
    // 绘制文本
    const lines = this.wrapText(this.text, availableWidth);
    const lineHeight = 36;  // 减小行高
    const totalHeight = lines.length * lineHeight;
    
    const startY = Math.max(
      this.padding.top,
      Math.min(
        (this.canvas.height - totalHeight) / 2,
        this.canvas.height - totalHeight - this.padding.bottom
      )
    );
    
    // 添加文本阴影
    this.ctx.shadowColor = 'rgba(255, 255, 255, 0.5)';
    this.ctx.shadowBlur = 2;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;
    
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        this.canvas.width / 2,
        startY + index * lineHeight
      );
    });
    
    // 重置阴影
    this.ctx.shadowColor = 'transparent';
  }

  async renderCalligraphy() {
    // 米色背景
    this.ctx.fillStyle = '#f5f5dc';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 添加纸张纹理
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.03)';
    for (let i = 0; i < this.canvas.height; i += 2) {
      this.ctx.fillRect(0, i, this.canvas.width, 1);
    }
    
    // 设置文本样式
    this.ctx.fillStyle = this.styles.textColor;
    this.ctx.font = `${this.styles.fontSize}px "LXGW WenKai", serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    
    // 计算可用宽度
    const availableWidth = this.canvas.width - (this.padding.left + this.padding.right);
    
    // 绘制文本
    const lines = this.wrapText(this.text, availableWidth);
    const lineHeight = 36;
    const totalHeight = lines.length * lineHeight;
    
    const startY = Math.max(
      this.padding.top,
      Math.min(
        (this.canvas.height - totalHeight) / 2,
        this.canvas.height - totalHeight - this.padding.bottom
      )
    );
    
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        this.canvas.width / 2,
        startY + index * lineHeight
      );
    });
  }

  async renderSocial() {
    // 创建渐变背景
    const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, 0);
    gradient.addColorStop(0, '#1da1f2');  // Twitter 蓝
    gradient.addColorStop(1, '#1da1f2');
    
    // 填充背景
    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 设置文本样式
    this.ctx.fillStyle = '#ffffff';
    this.ctx.font = `${this.styles.fontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    
    // 计算可用宽度
    const availableWidth = this.canvas.width - (this.padding.left + this.padding.right);
    
    // 绘制文本
    const lines = this.wrapText(this.text, availableWidth);
    const lineHeight = 36;
    const totalHeight = lines.length * lineHeight;
    
    const startY = Math.max(
      this.padding.top,
      Math.min(
        (this.canvas.height - totalHeight) / 2,
        this.canvas.height - totalHeight - this.padding.bottom
      )
    );
    
    // 添加文本阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.1)';
    this.ctx.shadowBlur = 10;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;
    
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        this.canvas.width / 2,
        startY + index * lineHeight
      );
    });
    
    // 重置阴影
    this.ctx.shadowColor = 'transparent';
  }

  wrapText(text, maxWidth) {
    const words = text.split('');
    const lines = [];
    let currentLine = '';
    
    words.forEach(word => {
      const testLine = currentLine + word;
      const metrics = this.ctx.measureText(testLine);
      
      if (metrics.width > maxWidth) {
        lines.push(currentLine);
        currentLine = word;
      } else {
        currentLine = testLine;
      }
    });
    
    lines.push(currentLine);
    return lines;
  }

  async toBlob() {
    return new Promise(resolve => {
      this.canvas.toBlob(resolve, 'image/png');
    });
  }
}

export default ImageGenerator; 