import { Provide, Inject } from '@midwayjs/decorator';
import { SqliteDataSourceManager } from '../manager/sqliteDataSourceManager';
import * as zlib from 'zlib';
import * as url from 'url';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DataSourceEntity } from '../entity/sys/data_source';

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

  async get3dTiles(d3tileUrl) {
    const url_path = new url.URL(d3tileUrl).pathname.split('/');
    //获取数据库的配置地址
    const assetId = url_path[2];
    const uri_segments = url_path.length;
    if (uri_segments === 4) {
      if (url_path[3] === 'tileset.json') {
        return this.response_3dtile('tileset.json', assetId);
      }
    }
    let key_value = '';
    for (let i = 3; i < uri_segments; i++) {
      if (i === 3) {
        key_value = key_value + url_path[i];
      } else {
        key_value = key_value + '/' + url_path[i];
      }
    }
    return this.response_3dtile(key_value, assetId);
  }

  async response_3dtile(key_value, assetId) {
    const query = "SELECT content FROM media WHERE key='" + key_value + "'";
    const dataTableSource = await this.dataSourceEntity.findOne({
      where: { name: assetId },
    });
    return this.getValue(query, 'dataSource' + dataTableSource.id);
  }

  async getValue(query, dataSourceId) {
    const queryResult = (await this.getSqliteConnected(
      dataSourceId,
      query
    )) as string;
    try {
      return new Promise((resolve, reject) => {
        zlib.gunzip(queryResult[0]['content'], (err, buffer) => {
          if (err) reject(err);
          //不能转string，转了就出错
          else resolve(buffer);
          // console.log(buffer.toString());
        });
      }).then(value => {
        return value;
      });
    } catch (error) {
      console.log('error：!!!' + error);
      return '';
    }
  }

  async getSqliteConnected(dataSource, sql) {
    return new Promise((resolve, reject) => {
      this.sqliteDataSourceManager
        .getDataSource(dataSource)
        .all(sql, [], (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
    }).then(value => {
      return value;
    });
  }
}
