import { relationalStore, ValuesBucket } from '@kit.ArkData'
import { NoteDBInfo } from '../models/Note'

class NoteDB {
  private store: relationalStore.RdbStore | null = null
  private tableName = 'note'
  private sqlCreate = `CREATE TABLE IF NOT EXISTS ${this.tableName} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        date_added INTEGER NOT NULL
      )`

  async getStoreInstance() {
    if (this.store) { return this.store }
    const store = await relationalStore.getRdbStore(getContext(), {
      name: 'note.db',
      securityLevel: relationalStore.SecurityLevel.S1
    })
    this.store = store
    return this.store
  }
  constructor() {
    this.getStoreInstance()
      .then(store => {
        store.executeSql(this.sqlCreate)
      })
  }

  // 新增
  async insert(item: NoteDBInfo) {
    //获取操作数据库的对象
    const store = await this.getStoreInstance()
    return store.insert(this.tableName, item)
  }

  // 查询数量
  async queryCount() {
    const store = await this.getStoreInstance()
    const predicates = new relationalStore.RdbPredicates(this.tableName)
    const resultSet = await store.query(predicates)
    return resultSet.rowCount > 0 ? resultSet.rowCount : 0
  }

  // 查询
  async query(id?: number) {
    const store = await this.getStoreInstance()
    const predicates = new relationalStore.RdbPredicates(this.tableName)
    // 倒序排列
    predicates.orderByDesc('id')
    // 如果有 id，添加 id 作为查询条件
    if (id) {
      predicates.equalTo('id', id)
    }
    const resultSet = await store.query(predicates)
    const list: NoteDBInfo[] = []
    while (resultSet.goToNextRow()) {
      // 获取行数据
      const row = resultSet.getRow() as NoteDBInfo
      // 追加到数组中
      list.push(row)
    }
    // 循环结束，释放结果集的内存空间（性能优化）
    resultSet.close()
    // 循环结束后，返回结果
    return list
  }

  async update(item: Partial<NoteDBInfo>) {
    if (!item.id) { return Promise.reject('id error') }
    const store = await this.getStoreInstance()
    const predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.equalTo('id', item.id)
    return store.update(item, predicates)
  }

  async delete(ids: number[]) {
    const store = await this.getStoreInstance()
    const predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.in('id', ids)
    return store.delete(predicates)
  }



}
export const noteDB = new NoteDB()
