import express, { Request, Response } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { Coordinate } from '../../interfaces/map';
import { generateTilesForZoomLevel } from '../../utils/tiles';
import axios from 'axios';

const router = express.Router()

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '..', '..', '..', 'public', 'temp'))
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname))
    }
})

const upload = multer({ storage: storage })

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

router.post('/upload', upload.single('file'), async (req: Request, res: Response) => {
    const { extentMinX, extentMinY, extentMaxX, extentMaxY, blX, blY, tlX, tlY, trX, trY, brX, brY } = req.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 }

    if (req.file) {
        for (let z = 0; z <= 21; z++) {
            await generateTilesForZoomLevel(uploadDir, tileFolder, req.file, [extentMinX, extentMinY, extentMaxX, extentMaxY], bottomLeft, topLeft, topRight, bottomRight, z)
        }
    }

    return res.status(200)
})

router.get('/tile/:provider/:z/:x/:y', async (req: Request, res: Response) => {
    const { provider, z, x, y } = req.params

    if (!['google', 'yandex', 'custom'].includes(provider)) {
        return res.status(400).send('Invalid provider')
    }

    const tilePath = provider === 'custom' ? path.join(tileFolder, provider, z, x, `${y}.png`) : path.join(tileFolder, provider, z, x, `${y}.jpg`)

    if (fs.existsSync(tilePath)) {
        return res.sendFile(tilePath)
    } else {
        if (provider !== 'custom') {
            try {
                const tileData = await fetchTileFromAPI(provider, z, x, y)

                fs.mkdirSync(path.dirname(tilePath), { recursive: true })

                fs.writeFileSync(tilePath, tileData)

                res.contentType('image/jpeg')
                res.send(tileData)
            } catch (error) {
                console.error('Error fetching tile from API:', error)
                res.status(500).send('Error fetching tile from API')
            }
        } else {
            res.status(404).send('Tile is not generated or not provided')
        }
    }
})

const fetchTileFromAPI = async (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
}

export default router