import { Injectable } from '@angular/core';
import * as Parse from 'parse';

@Injectable({
  providedIn: 'root'
})
export class ParseService {
serverURL = "http://web2023.fmode.cn:9999/parse"
  constructor() { }

  async getDongTai(): Promise<Parse.Object[]> {
    const DongTai = Parse.Object.extend('DongTai');
    const query = new Parse.Query(DongTai);
    query.descending('time');
    return await query.find();
  }

  async searchDongTai(keyword: string): Promise<Parse.Object[]> {
    const DongTai = Parse.Object.extend('DongTai');
    const query = new Parse.Query(DongTai);
    query.contains('biaoti', keyword);
    query.descending('time');
    return await query.find();
  }

  async createDongTai(biaoti: string, neirong: string, time: string, imageFile?: File): Promise<Parse.Object> {
    const DongTai = Parse.Object.extend('DongTai');
    const dongtai = new DongTai();
    dongtai.set('biaoti', biaoti);
    dongtai.set('neirong', neirong);
    dongtai.set('time', time);

    if (imageFile) {
      const parseFile = new Parse.File(imageFile.name, imageFile);
      await parseFile.save();
      dongtai.set('image', parseFile);
    }

    return await dongtai.save();
  }

  async deleteDongTai(id: string): Promise<void> {
    const DongTai = Parse.Object.extend('DongTai');
    const query = new Parse.Query(DongTai);
    const dongtai = await query.get(id);
    await dongtai.destroy();
  }
}
