// drift-bottle.component.ts
import { Component, OnInit } 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';

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

  constructor(
    private router: Router,
    private modalCtrl: ModalController,
    private http: HttpClient
  ) {}

  ngOnInit() {}

  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];

      bottleToCatch.set("status", "catched");
      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'])
  }
}