import { Component, OnInit, OnDestroy, Renderer2, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { openThrowDriftBottleModal } from '../throw-drift-bottle/throw-drift-bottle.component';
import { ModalController } from '@ionic/angular/standalone';
import { HttpClient } from '@angular/common/http';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { UserService } from 'src/app/user.service'; // 假设这是你的用户服务
import { CommonModule } from '@angular/common'; // 导入 CommonModule

@Component({
  selector: 'app-drift-bottle',
  templateUrl: './drift-bottle.component.html',
  styleUrls: ['./drift-bottle.component.scss'],
  standalone: true,
  imports: [
    IonicModule,
    CommonModule, // 添加 CommonModule
    // 其他导入项...
  ]
})
export class DriftBottleComponent implements OnInit, OnDestroy {
  alertHeader: string = '';
  alertMessage: string = '';

  @ViewChild('backgroundAudio', { static: false }) audioElement!: ElementRef<HTMLAudioElement>;

  constructor(
    private router: Router,
    private modalCtrl: ModalController,
    private http: HttpClient,
    private renderer: Renderer2,
    private userService: UserService // 注入用户服务
  ) {}

  ngOnInit() {
    if (this.audioElement && this.audioElement.nativeElement) {
      const audio = this.audioElement.nativeElement;
      audio.loop = true;
      audio.play().catch(error => {
        console.error('Failed to play audio:', error);
      });
    } else {
      console.warn('Audio element not found');
    }
  }

  ngOnDestroy() {
    if (this.audioElement && this.audioElement.nativeElement) {
      const audio = this.audioElement.nativeElement;
      audio.pause();
      audio.currentTime = 0; // 重置音频时间
      console.log('Audio element paused and reset');
    } else {
      console.warn('Audio element not found during destroy');
    }
    console.log('ngOnDestroy called');
  }

  throwDriftBottleModal() {
    openThrowDriftBottleModal(this.modalCtrl);
  }

  catchDriftBottle() {
    const query = new CloudQuery("DriftBottle");
    query.equalTo("status", "drifting");

    query.find().then((driftingBottles: any[]) => {
      if (driftingBottles.length === 0) {
        this.alertHeader = '失败';
        this.alertMessage = '没捞到…';
        return;
      }

      const randomIndex = Math.floor(Math.random() * driftingBottles.length);
      const bottleToCatch = driftingBottles[randomIndex];

      const username = this.userService.getUsername(); // 获取当前用户的用户名
      if (!username) {
        console.error('用户未登录或未找到用户名');
        this.alertHeader = '错误';
        this.alertMessage = '用户未登录，请先登录。';
        return;
      }

      bottleToCatch.set("status", "caught");
      bottleToCatch.set("catcher", username); // 设置打捞者
      bottleToCatch.set("catchTime", new Date()); // 设置打捞时间

      bottleToCatch.save().then(() => {
        this.alertHeader = '成功';
        this.alertMessage = '捞到啦！快去看看吧！';
      }).catch((err: any) => {
        console.error('更新漂流瓶状态时出错:', err);
        this.alertHeader = '错误';
        this.alertMessage = '发生错误，请重试。';
      });
    }).catch((err) => {
      console.error('获取漂流瓶时出错:', err);
      this.alertHeader = '错误';
      this.alertMessage = '发生错误，请重试。';
    });
  }

  dismissAlert() {
    this.alertHeader = '';
    this.alertMessage = '';
  }

  goMydriftbottle() {
    this.router.navigate(['tabs/my-drift-bottle']);
  }
}