import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay, map } from 'rxjs/operators';
import { SceneParams, SceneTemplate } from '../models/requirement-mapping.interface';

export interface AtmospherePreviewOptions {
  width?: number;
  height?: number;
  quality?: 'low' | 'medium' | 'high';
  style?: 'realistic' | 'artistic' | 'conceptual';
}

export interface PreviewGenerationResult {
  url: string;
  thumbnailUrl: string;
  metadata: {
    sceneType: SceneTemplate;
    generatedAt: Date;
    parameters: SceneParams;
    processingTime: number;
  };
}

@Injectable({
  providedIn: 'root'
})
export class AtmospherePreviewService {

  constructor() {}

  /**
   * 生成氛围感预览图
   */
  generateAtmospherePreview(
    params: SceneParams, 
    sceneType: SceneTemplate,
    options: AtmospherePreviewOptions = {}
  ): Observable<PreviewGenerationResult> {
    const startTime = Date.now();
    
    // 设置默认选项
    const defaultOptions: AtmospherePreviewOptions = {
      width: 800,
      height: 600,
      quality: 'medium',
      style: 'realistic'
    };
    
    const finalOptions = { ...defaultOptions, ...options };
    
    // 模拟异步生成过程
    return of(null).pipe(
      delay(2000), // 模拟生成时间
      map(() => {
        const processingTime = Date.now() - startTime;
        const previewUrl = this.generatePreviewUrl(params, sceneType, finalOptions);
        const thumbnailUrl = this.generateThumbnailUrl(previewUrl);
        
        return {
          url: previewUrl,
          thumbnailUrl: thumbnailUrl,
          metadata: {
            sceneType,
            generatedAt: new Date(),
            parameters: params,
            processingTime
          }
        };
      })
    );
  }

  /**
   * 批量生成多个场景的预览图
   */
  generateMultiplePreviews(
    scenesWithParams: Array<{ params: SceneParams; sceneType: SceneTemplate }>,
    options: AtmospherePreviewOptions = {}
  ): Observable<PreviewGenerationResult[]> {
    const previews$ = scenesWithParams.map(({ params, sceneType }) =>
      this.generateAtmospherePreview(params, sceneType, options)
    );
    
    // 这里应该使用 forkJoin 来并行生成，但为了简化，我们串行处理
    return of(null).pipe(
      delay(3000),
      map(() => {
        return scenesWithParams.map(({ params, sceneType }) => {
          const previewUrl = this.generatePreviewUrl(params, sceneType, options);
          return {
            url: previewUrl,
            thumbnailUrl: this.generateThumbnailUrl(previewUrl),
            metadata: {
              sceneType,
              generatedAt: new Date(),
              parameters: params,
              processingTime: 2000
            }
          };
        });
      })
    );
  }

  /**
   * 根据参数生成预览图URL
   */
  private generatePreviewUrl(
    params: SceneParams, 
    sceneType: SceneTemplate, 
    options: AtmospherePreviewOptions
  ): string {
    // 生成基于参数的哈希值
    const paramHash = this.generateParameterHash(params);
    const sceneId = sceneType.toString().toLowerCase();
    const quality = options.quality || 'medium';
    const style = options.style || 'realistic';
    
    // 在实际应用中，这里应该调用AI图像生成API
    // 目前返回模拟的预览图URL
    const baseUrl = '/assets/atmosphere-previews/';
    return `${baseUrl}${sceneId}_${style}_${quality}_${paramHash}.jpg`;
  }

  /**
   * 生成缩略图URL
   */
  private generateThumbnailUrl(previewUrl: string): string {
    return previewUrl.replace('.jpg', '_thumb.jpg');
  }

  /**
   * 根据场景参数生成哈希值
   */
  private generateParameterHash(params: SceneParams): string {
    const hashInput = JSON.stringify({
      lighting: {
        intensity: params.lighting.primaryLight.intensity,
        temperature: params.lighting.primaryLight.temperature,
        direction: params.lighting.primaryLight.direction
      },
      environment: {
        setting: params.environment.setting,
        atmosphere: params.environment.atmosphere
      },
      style: {
        renderStyle: params.style.renderStyle,
        colorGrading: params.style.colorGrading
      }
    });
    
    // 简单的哈希函数
    let hash = 0;
    for (let i = 0; i < hashInput.length; i++) {
      const char = hashInput.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
    
    return Math.abs(hash).toString(16).substring(0, 8);
  }

  /**
   * 获取预设的氛围感预览图
   */
  getPresetPreviews(sceneType: SceneTemplate): string[] {
    const presetMap: Record<SceneTemplate, string[]> = {
      [SceneTemplate.LIVING_ROOM_MODERN]: [
        '/assets/presets/living_room_modern_1.jpg',
        '/assets/presets/living_room_modern_2.jpg',
        '/assets/presets/living_room_modern_3.jpg'
      ],
      [SceneTemplate.LIVING_ROOM_CLASSIC]: [
        '/assets/presets/living_room_classic_1.jpg',
        '/assets/presets/living_room_classic_2.jpg'
      ],
      [SceneTemplate.BEDROOM_COZY]: [
        '/assets/presets/bedroom_cozy_1.jpg',
        '/assets/presets/bedroom_cozy_2.jpg'
      ],
      [SceneTemplate.BEDROOM_MINIMAL]: [
        '/assets/presets/bedroom_minimal_1.jpg'
      ],
      [SceneTemplate.KITCHEN_CONTEMPORARY]: [
        '/assets/presets/kitchen_contemporary_1.jpg',
        '/assets/presets/kitchen_contemporary_2.jpg'
      ],
      [SceneTemplate.KITCHEN_TRADITIONAL]: [
        '/assets/presets/kitchen_traditional_1.jpg'
      ],
      [SceneTemplate.BATHROOM_LUXURY]: [
        '/assets/presets/bathroom_luxury_1.jpg'
      ],
      [SceneTemplate.BATHROOM_MINIMAL]: [
        '/assets/presets/bathroom_minimal_1.jpg'
      ],
      [SceneTemplate.OFFICE_MODERN]: [
        '/assets/presets/office_modern_1.jpg'
      ],
      [SceneTemplate.OFFICE_TRADITIONAL]: [
        '/assets/presets/office_traditional_1.jpg'
      ],
      [SceneTemplate.DINING_FORMAL]: [
        '/assets/presets/dining_formal_1.jpg'
      ],
      [SceneTemplate.DINING_CASUAL]: [
        '/assets/presets/dining_casual_1.jpg'
      ],
      [SceneTemplate.STUDIO_APARTMENT]: [
        '/assets/presets/studio_apartment_1.jpg'
      ],
      [SceneTemplate.OUTDOOR_PATIO]: [
        '/assets/presets/outdoor_patio_1.jpg'
      ],
      [SceneTemplate.OUTDOOR_GARDEN]: [
        '/assets/presets/outdoor_garden_1.jpg'
      ]
    };
    
    return presetMap[sceneType] || [];
  }

  /**
   * 验证预览图URL是否有效
   */
  validatePreviewUrl(url: string): Observable<boolean> {
    return new Observable(observer => {
      const img = new Image();
      img.onload = () => {
        observer.next(true);
        observer.complete();
      };
      img.onerror = () => {
        observer.next(false);
        observer.complete();
      };
      img.src = url;
    });
  }

  /**
   * 获取预览图的元数据
   */
  getPreviewMetadata(url: string): Observable<any> {
    // 模拟获取图片元数据
    return of({
      dimensions: { width: 800, height: 600 },
      fileSize: '245KB',
      format: 'JPEG',
      colorProfile: 'sRGB',
      generatedAt: new Date(),
      aiModel: 'AtmosphereGen-v2.1'
    }).pipe(delay(500));
  }
}