import { Injectable } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';

@Injectable()
export class EmsService {
    constructor(
        @InjectDataSource('emsConnection')
        private dataSource: DataSource
    ) { }

    async getTypeRoles(): Promise<any[]> {
        const result = await this.dataSource.query(`
            SELECT * FROM "TypeRoles";
            `)
        return result
    }

    async getImages(city_id?: number, offset?: number, limit?: number): Promise<any[]> {
        if (city_id) {
            const result = await this.dataSource.query(`
            SELECT * FROM "images"
            WHERE city_id = @0
            ORDER BY city_id
            OFFSET @1 ROWS
            FETCH NEXT @2 ROWS ONLY;
            `, [city_id, offset || 0, limit || 10])
            return result
        } else {
            const result = await this.dataSource.query(`
            SELECT * FROM "images"
            ORDER BY city_id
            OFFSET @0 ROWS
            FETCH NEXT @1 ROWS ONLY;
            `, [offset || 0, limit || 10])
            return result
        }
    }

    async getFigures(year: number, city_id: number, offset?: number, limit?: number): Promise<any[]> {
        const result = await this.dataSource.query(`
            SELECT * FROM figures f
            JOIN vObjects o ON f.object_id = o.object_id WHERE o.id_city = @0 AND f.year = @1
            ORDER BY f.year
            OFFSET @2 ROWS
            FETCH NEXT @3 ROWS ONLY;
            `, [city_id, year, Number(offset) || 0, Number(limit) || 10])
        return result
    }
}
