import { Injectable, Logger } from '@nestjs/common';
import { UploadDTO } from './dto/upload';
import { generateTilesForZoomLevel } from './utils/tiles';
import { join } from 'path';
import axios from 'axios';
import { randomUUID } from 'crypto';

export interface Coordinate {
    x: number,
    y: number
}

const tileFolder = join(__dirname, '..', '..', '..', 'storage', 'tile_data')
const uploadDir = join(__dirname, '..', '..', '..', 'storage', 'temp')

@Injectable()
export class TilesService {
    async fetchTileFromAPI(provider: string, z: string, x: string, y: string): Promise<Buffer> {
        const url = provider === 'google'
            ? `https://khms2.google.com/kh/v=984?x=${x}&y=${y}&z=${z}`
            : `https://core-sat.maps.yandex.net/tiles?l=sat&x=${x}&y=${y}&z=${z}&scale=1&lang=ru_RU`

        const response = await axios.get(url, { responseType: 'arraybuffer' })
        return response.data
    }

    async processUpload(file: Express.Multer.File, body: UploadDTO) {
        const {
            extentMinX,
            extentMinY,
            extentMaxX,
            extentMaxY,
            blX,
            blY,
            tlX,
            tlY,
            trX,
            trY,
            brX,
            brY
        } = body

        const bottomLeft: Coordinate = { x: blX, y: blY }
        const topLeft: Coordinate = { x: tlX, y: tlY }
        const topRight: Coordinate = { x: trX, y: trY }
        const bottomRight: Coordinate = { x: brX, y: brY }

        Logger.log(`generating to ${uploadDir} ${tileFolder} ${randomUUID().toString()}`)
        if (file) {
            for (let z = 0; z <= 21; z++) {
                await generateTilesForZoomLevel(
                    uploadDir,
                    tileFolder,
                    file,
                    [extentMinX, extentMinY, extentMaxX, extentMaxY],
                    bottomLeft,
                    topLeft,
                    topRight,
                    bottomRight,
                    z,
                )
            }
        }
    }
}
