import { Provide, Inject } from '@midwayjs/decorator';
import { SqliteDataSourceManager } from '../manager/sqliteDataSourceManager';
import { DataSourceEntity } from '../entity/sys/data_source';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as MBTiles from '@mapbox/mbtiles';
import { resolve } from 'path';

@Provide()
export class mbTileService {
  @Inject()
  sqliteDataSourceManager: SqliteDataSourceManager;
  @InjectEntityModel(DataSourceEntity)
  dataSourceEntity: Repository<DataSourceEntity>;

  async getMbTiles(t, z, x, y) {
    //获取数据库的配置地址
    const dataTableSource = await this.dataSourceEntity.findOne({
      where: { name: t },
    });
    const mbtilesLocation = resolve(dataTableSource.database);
    try {
      return new Promise((resolve, reject) => {
        new MBTiles(mbtilesLocation, (err, mbtiles) => {
          if (err) reject(err);
          mbtiles.getTile(
            Number(z),
            Number(x),
            (1 << Number(z)) - 1 - Number(y),
            (err, tile, headers) => {
              if (err) {
                reject('Tile rendering error: ' + err + '\n');
              } else {
                console.log(z);
                resolve(tile);
              }
            }
          );
        });
      }).then(value => {
        return value;
      });
    } catch (error) {
      console.log('error：!!!' + error);
      return '';
    }
  }
}
