part of '../entities.dart';

/// Created by Haoyi on 2023/10/11
///
//
@JsonSerializable()
class AwardEntity implements Identifiable {
  static const tbName = "awards";
  static const dbId = "id";

  static const dbAchieved = "progress";
  static const dbYear = "yr";
  static const dbYearMonth = "ym";
  static const dbUpdateAt = "upt";

  @override
  @JsonKey(name: dbId)
  final String id;

  @JsonKey(name: dbAchieved, defaultValue: 0)
  final int achieved;

  @JsonKey(name: dbYear, defaultValue: 0)
  final int year;

  @JsonKey(name: dbYearMonth, defaultValue: 0)
  final int yearMonth;

  @JsonKey(name: dbUpdateAt, defaultValue: 0)
  final int updateAt;

  AwardEntity(
      {required this.id,
      required this.achieved,
      required this.year,
      required this.yearMonth,
      required this.updateAt});

  static String generateId(DateTime focusDate) => DateTimeUtils.yyyyMMBuild(focusDate);

  static AwardEntity create(DateTime focusDate, int achieved) {
    return AwardEntity(
        id: generateId(focusDate),
        achieved: achieved,
        year: focusDate.year,
        yearMonth: DateTimeUtils.generateYearMonthNum(focusDate),
        updateAt: DateTimeUtils.currentTimeInMillis());
  }

  factory AwardEntity.fromMap(Map<String, dynamic> json) => _$AwardEntityFromJson(json);

  Map<String, dynamic> toMap() => _$AwardEntityToJson(this);

  static Future createTable(Transaction delegate) async {
    // v1
    const v1Fields = "$dbId TEXT PRIMARY KEY,"
        "$dbAchieved INTEGER NOT NULL DEFAULT 0,"
        "$dbYear INTEGER NOT NULL,"
        "$dbYearMonth INTEGER NOT NULL,"
        "$dbUpdateAt INTEGER NOT NULL";

    const cmd = "CREATE TABLE $tbName ("
        "$v1Fields"
        ");";

    Log.d("#### cmd: $cmd");

    await delegate.execute(cmd);
    await delegate.execute("CREATE INDEX award_idx ON $tbName ($dbId);");
    await delegate.execute("CREATE INDEX award_ym_idx ON $tbName ($dbYearMonth)");
    await delegate.execute("CREATE INDEX award_yr_idx ON $tbName ($dbYear)");
  }

  @override
  String toString() {
    return 'AwardEntity{id: $id, achieved: $achieved, year: $year, yearMonth: $yearMonth, updateAt: $updateAt}';
  }
}
