/// <reference path="../pb_data/types.d.ts" />
migrate(
  app => {
    let col = app.findCollectionByNameOrId('scoring_judges');
    let names = col.fields.fieldNames();

    if (!names.includes('isAbsent')) {
      return app.save(col);
    }

    if (!names.includes('isAutojudge')) {
      col.fields.addAt(
        col.fields.length,
        new Field({
          hidden: false,
          id: 'bool1779600001',
          name: 'isAutojudge',
          presentable: false,
          required: false,
          system: false,
          type: 'bool'
        })
      );
      app.save(col);
      col = app.findCollectionByNameOrId('scoring_judges');
    }

    const pageSize = 200;
    let offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(col.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        const fromAbsent = record.get('isAbsent') === true;
        const already = record.get('isAutojudge') === true;
        record.set('isAutojudge', fromAbsent || already);
        app.save(record);
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    col = app.findCollectionByNameOrId('scoring_judges');
    if (col.fields.fieldNames().includes('isAbsent')) {
      col.fields.removeByName('isAbsent');
    }
    return app.save(col);
  },
  app => {
    let col = app.findCollectionByNameOrId('scoring_judges');
    let names = col.fields.fieldNames();

    if (!names.includes('isAutojudge') || names.includes('isAbsent')) {
      return app.save(col);
    }

    col.fields.addAt(
      col.fields.length,
      new Field({
        hidden: false,
        id: 'bool1779500000',
        name: 'isAbsent',
        presentable: false,
        required: false,
        system: false,
        type: 'bool'
      })
    );
    app.save(col);
    col = app.findCollectionByNameOrId('scoring_judges');

    const pageSize = 200;
    let offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(col.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        record.set('isAbsent', record.get('isAutojudge') === true);
        app.save(record);
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    col = app.findCollectionByNameOrId('scoring_judges');
    if (col.fields.fieldNames().includes('isAutojudge')) {
      col.fields.removeByName('isAutojudge');
    }
    return app.save(col);
  }
);
