/**********************************************************************************************
    Copyright (C) 2011 Oliver Eichler oliver.eichler@gmx.de

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

**********************************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include <list>
#include <vector>
#include <string>

#include <gdal_priv.h>
#include <projects.h>
#include <ogr_spatialref.h>
#include <jpeglib.h>

#ifndef _MKSTR_1
#define _MKSTR_1(x)    #x
#define _MKSTR(x)      _MKSTR_1(x)
#endif

#define VER_STR       _MKSTR(VER_MAJOR)"."_MKSTR(VER_MINOR)"."_MKSTR(VER_STEP)
#define WHAT_STR      "map2jnx, Version " VER_STR

#define JNX_MAX_TILES 6250
#define JNX_MAX_TILE_SIZE 1024

#pragma pack(1)

struct jnx_hdr_t
{
    jnx_hdr_t(): version(0x00000003), devid(0), expire(0), crc(0), signature(0), signature_offset(0){}
    uint32_t version;           // byte 00000000..00000003
    uint32_t devid;             // byte 00000004..00000007
    int32_t  top;               // byte 00000014..00000017
    int32_t  right;             // byte 00000010..00000013
    int32_t  bottom;            // byte 0000000C..0000000F
    int32_t  left;              // byte 00000008..0000000B
    uint32_t details;           // byte 00000018..0000001B
    uint64_t expire;            // byte 0000001C..00000023
    uint32_t crc;               // byte 00000024..00000027
    uint32_t signature;         // byte 00000028..0000002B
    uint32_t signature_offset;  // byte 0000002C..0000002F
};


struct jnx_level_t
{
    jnx_level_t(): nTiles(0), offset(0), scale(){}

    uint32_t nTiles;
    uint32_t offset;
    uint32_t scale;
};

struct jnx_tile_t
{
    jnx_tile_t() : top(0), right(0), bottom(0), left(0), width(0), height(0), size(0), offset(0){}
    int32_t  top;
    int32_t  right;
    int32_t  bottom;
    int32_t  left;
    uint16_t width;
    uint16_t height;
    uint32_t size;
    uint32_t offset;
};


#ifdef WIN32
#pragma pack()
#else
#pragma pack(0)
#endif

struct file_t
{
    file_t(): dataset(0), pj(0){memset(colortable,0, sizeof(colortable));}
    ~file_t()
    {
        if(dataset) delete dataset;
        if(pj) pj_free(pj);
    }

    bool operator<(const file_t& other)
    {
        return (xscale > other.xscale);
    }

    std::string     filename;
    std::string     projection;
    GDALDataset *   dataset;
    PJ *            pj;
    uint32_t        width;
    uint32_t        height;
    double          xscale;
    double          yscale;
    double          xref1;
    double          yref1;
    double          xref2;
    double          yref2;

    double          lon1;
    double          lat1;
    double          lon2;
    double          lat2;

    uint32_t        colortable[256];

};

struct level_t : public jnx_level_t
{
    std::list<file_t *> files;
    uint32_t tileSize;
};

/// number of used levels
static int32_t nLevels;
/// up to five levels. nLevels gives the actual count
static level_t levels[5];
/// information about all files
static std::list<file_t> files;
/// the target lon/lat WGS84 projection
static PJ * wgs84;
/// the JNX file header to be copied to the outfile
static jnx_hdr_t jnx_hdr;
/// the tile information table for all 5 levels
static jnx_tile_t tileTable[JNX_MAX_TILES * 5];
/// tile buffer for 8 bit palette tiles, private to readTile
static uint8_t  tileBuf8Bit[JNX_MAX_TILE_SIZE * JNX_MAX_TILE_SIZE] = {0};
/// tile buffer for 24 bit raw RGB tiles, private to writeTile
static uint8_t tileBuf24Bit[JNX_MAX_TILE_SIZE * JNX_MAX_TILE_SIZE * 3] = {0};
/// tile buffer for 32 bit raw RGBA tiles
static uint32_t tileBuf32Bit[JNX_MAX_TILE_SIZE * JNX_MAX_TILE_SIZE] = {0};

static void prinfFileinfo(const file_t& file)
{
    printf("\n\n----------------------");
    printf("\n%s:", file.filename.c_str());
    printf("\nprojection: %s", file.projection.c_str());
    printf("\nwidth: %i pixel height: %i pixel", file.width, file.height);

    if(pj_is_latlong(file.pj))
    {
        printf("\narea (top/left, bottom/right): %f %f, %f %f", file.lat1, file.lon1, file.lat2, file.lon2);
        printf("\nxscale: %f °/px, yscale: %f °/px", file.xscale, file.yscale);
    }
    else
    {
        printf("\narea (top/left, bottom/right): %f %f, %f %f", file.lat1, file.lon1, file.lat2, file.lon2);
        printf("\nxscale: %f m/px, yscale: %f m/px", file.xscale, file.yscale);
    }
}

bool readTile(uint32_t xoff, uint32_t yoff, uint32_t xsize, uint32_t ysize, file_t& file, uint32_t * output)
{
    GDALDataset * dataset = file.dataset;
    int32_t rasterBandCount = dataset->GetRasterCount();

    memset(output,-1, sizeof(uint32_t) * xsize * ysize);

    if(rasterBandCount == 1)
    {
        GDALRasterBand * pBand;
        pBand = dataset->GetRasterBand(1);
        if(pBand->RasterIO(GF_Read,(int)xoff,(int)yoff, xsize, ysize, tileBuf8Bit,xsize,ysize,GDT_Byte,0,0) == CE_Failure)
        {
            return false;
        }

        for(int i = 0; i < (xsize * ysize); i++)
        {
            output[i] = file.colortable[tileBuf8Bit[i]];
        }
    }
    else
    {
        for(int b = 1; b <= rasterBandCount; ++b)
        {
            GDALRasterBand * pBand;
            pBand = dataset->GetRasterBand(b);

            uint32_t mask = ~(0x000000FF << (8*(b-1)));

            if(pBand->RasterIO(GF_Read,(int)xoff,(int)yoff, xsize, ysize, tileBuf8Bit,xsize,ysize,GDT_Byte,0,0) == CE_Failure)
            {
                return false;
            }

            for(int i = 0; i < (xsize * ysize); i++)
            {
                uint32_t pixel = output[i];

                pixel &= mask;
                pixel |= tileBuf8Bit[i];
                output[i] = pixel;
            }
        }
    }

    return true;
}

uint32_t writeTile(uint32_t xsize, uint32_t ysize, uint32_t * raw_image, FILE * fid)
{
    uint32_t size = 0;

    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    JSAMPROW row_pointer[1];


    for(uint32_t r = 0; r < ysize; r++)
    {
        for(uint32_t c = 0; c < xsize; c++)
        {
            uint32_t pixel = raw_image[r * xsize + c];
            tileBuf24Bit[r * xsize * 3 + c * 3]     =  pixel        & 0x0FF;
            tileBuf24Bit[r * xsize * 3 + c * 3 + 1] = (pixel >>  8) & 0x0FF;
            tileBuf24Bit[r * xsize * 3 + c * 3 + 2] = (pixel >> 16) & 0x0FF;
        }
    }


    FILE *outfile = fopen( ".tmp", "wb" );


    if(outfile == 0)
    {
        printf(" ");
    }


    cinfo.err = jpeg_std_error( &jerr );
    jpeg_create_compress(&cinfo);
    jpeg_stdio_dest(&cinfo, outfile);

    cinfo.image_width       = xsize;
    cinfo.image_height      = ysize;
    cinfo.input_components  = 3;
    cinfo.in_color_space    = JCS_RGB;

    jpeg_set_defaults( &cinfo );
    jpeg_start_compress( &cinfo, TRUE );

    while( cinfo.next_scanline < cinfo.image_height )
    {
        row_pointer[0] = (JSAMPLE*)&tileBuf24Bit[ cinfo.next_scanline * cinfo.image_width *  cinfo.input_components];
        jpeg_write_scanlines( &cinfo, row_pointer, 1 );
    }
    /* similar to read file, clean up after we're done compressing */
    jpeg_finish_compress( &cinfo );
    jpeg_destroy_compress( &cinfo );
    fclose( outfile );

    /// @todo do the jpeg compression in memory
    FILE *infile = fopen( ".tmp", "rb");
    fseek(infile, 0, SEEK_END);
    size = ftell(infile) - 2;
    fseek(infile, 2, SEEK_SET);
    fread(tileBuf24Bit, size, 1, infile);
    fwrite(tileBuf24Bit, size, 1, fid);

    fclose(infile);
    return size;
}

int main(int argc, char ** argv)
{
    long tileTableStart = 0;
    uint32_t tileCnt    = 0;
    uint32_t tilesTotal = 0;
    char projstr[1024];
    OGRSpatialReference oSRS;

    printf("\n****** %s ******\n", WHAT_STR);

    if(argc < 2)
    {
        printf("\nusage: map2jnx <file1> <file2> ... <fileN> <outputfile>\n");
        printf("\n");
        exit(-1);
    }

    GDALAllRegister();
    wgs84 = pj_init_plus("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");

    // read geo information from input files
    files.resize(argc - 2);
    for(int i = 1; i < (argc - 1); i++)
    {
        GDALDataset * dataset = (GDALDataset*)GDALOpen(argv[i],GA_ReadOnly);
        if(dataset == 0)
        {
            printf("\nFailed to open %s\n", argv[i]);
            exit(-1);
        }

        PJ *   pj;
        char * ptr = projstr;

        strncpy(projstr,dataset->GetProjectionRef(),sizeof(projstr));
        oSRS.importFromWkt(&ptr);
        oSRS.exportToProj4(&ptr);

        pj = pj_init_plus(ptr);
        if(pj == 0)
        {
            printf("\nUnknown projection in file %s\n", argv[i]);
            exit(-1);
        }

        double adfGeoTransform[6];
        dataset->GetGeoTransform( adfGeoTransform );

        std::list<file_t>::iterator f = files.begin();
        std::advance(f, i - 1);

        file_t& file    = *f;
        file.filename   = argv[i];
        file.projection = ptr;
        file.dataset    = dataset;
        file.pj         = pj;
        file.width      = dataset->GetRasterXSize();
        file.height     = dataset->GetRasterYSize();
        file.xscale     = adfGeoTransform[1];
        file.yscale     = adfGeoTransform[5];
        file.xref1      = adfGeoTransform[0];
        file.yref1      = adfGeoTransform[3];
        file.xref2      = file.xref1 + file.width  * file.xscale;
        file.yref2      = file.yref1 + file.height * file.yscale;

        if(pj_is_latlong(file.pj))
        {
            file.lon1 = file.xref1;
            file.lat1 = file.yref1;
            file.lon2 = file.xref2;
            file.lat2 = file.yref2;
        }
        else
        {
            file.lon1 = file.xref1;
            file.lat1 = file.yref1;
            file.lon2 = file.xref2;
            file.lat2 = file.yref2;

            pj_transform(pj,wgs84,1,0,&file.lon1,&file.lat1,0);
            pj_transform(pj,wgs84,1,0,&file.lon2,&file.lat2,0);

            file.lon1 *= RAD_TO_DEG;
            file.lat1 *= RAD_TO_DEG;
            file.lon2 *= RAD_TO_DEG;
            file.lat2 *= RAD_TO_DEG;
        }

        // fill color table if necessary
        GDALRasterBand * pBand;
        pBand = dataset->GetRasterBand(1);

        if(pBand->GetColorInterpretation() == GCI_PaletteIndex)
        {
            GDALColorTable * pct = pBand->GetColorTable();
            for(int c=0; c < pct->GetColorEntryCount(); ++c)
            {
                const GDALColorEntry& e = *pct->GetColorEntry(c);
                file.colortable[c] = e.c1 | (e.c2 << 8) | (e.c3 << 16) | (e.c4 << 24);
            }
        }
        else if(pBand->GetColorInterpretation() ==  GCI_GrayIndex )
        {
            for(int c=0; c < 256; ++c)
            {
                file.colortable[c] = c | (c << 8) | (c << 16) | 0xFF000000;
            }
        }

        int success = 0;
        int idx = pBand->GetNoDataValue(&success);

        if(success)
        {
            file.colortable[idx] &= 0x00FFFFFF;
        }
    }

    // apply sorted files to levels and extract file header data
    double right    = -180.0;
    double top      =  -90.0;
    double left     =  180.0;
    double bottom   =   90.0;

    double scale = 0.0;
    files.sort();
    std::list<file_t>::iterator f;
    for(f = files.begin(); f != files.end(); f++)
    {
        file_t& file = *f;
        prinfFileinfo(file);

        if(file.lon1 < left)    left   = file.lon1;
        if(file.lat1 > top)     top    = file.lat1;
        if(file.lat2 < bottom)  bottom = file.lat2;
        if(file.lon2 > right)   right  = file.lon2;

        if(scale != 0.0 && ((fabs(scale - file.xscale)) / scale) > 0.02)
        {
            nLevels++;
            if(nLevels > 4)
            {
                printf("\nToo many different detail levels.\n");
                exit(-1);
            }
        }
        scale = file.xscale;

        levels[nLevels].files.push_back(&file);
    }
    nLevels++;

    FILE * fid = fopen(argv[argc-1],"wb");
    if(fid == 0)
    {
        printf("\nFailed to create file %s\n", argv[argc-1]);
        exit(-1);
    }

    jnx_hdr.left    = (left   * 0x7FFFFFFF) / 180;
    jnx_hdr.top     = (top    * 0x7FFFFFFF) / 180;
    jnx_hdr.right   = (right  * 0x7FFFFFFF) / 180;
    jnx_hdr.bottom  = (bottom * 0x7FFFFFFF) / 180;

    jnx_hdr.details = nLevels;

    printf("\n\n======== map header ========");
    printf("\nmap area (top/left, bottom/right): %f %f, %f %f", left, top, right, bottom);
    printf("\n                                   %08X %08X, %08X %08X", jnx_hdr.left, jnx_hdr.top, jnx_hdr.right, jnx_hdr.bottom);
    printf("\nnumber of detail levels:           %i", jnx_hdr.details);

    fwrite(&jnx_hdr, sizeof(jnx_hdr), 1, fid);


    // get all information to write the table of detail levels and the dummy tile table
    for(int i = 0; i < nLevels; i++)
    {
        uint32_t size   = 256;
        level_t& level  = levels[i];
        std::list<file_t *>::iterator f;
        double scale    = 0.0;
        bool isLonLat   = false;

        while(size <= JNX_MAX_TILE_SIZE)
        {
            level.nTiles    = 0;
            level.tileSize  = size;
            for(f = level.files.begin(); f != level.files.end(); f++)
            {
                file_t& file  = *(*f);
                double xTiles = file.width  / double(size);
                double yTiles = file.height / double(size);
                level.nTiles += int(ceil(xTiles)) * int(ceil(yTiles));

                scale         = file.xscale;
                isLonLat      = pj_is_latlong(file.pj);
            }

            if(level.nTiles < JNX_MAX_TILES)
            {
                break;
            }
            size <<= 1;
        }


        level.offset = sizeof(jnx_hdr_t) + sizeof(jnx_level_t) * nLevels + tilesTotal * sizeof(jnx_tile_t);
        if(isLonLat)
        {
            level.scale = int(scale * 6.9924e+07);
        }
        else
        {
            level.scale = int(scale * 628.14);
        }
        tilesTotal += level.nTiles;

        fwrite(&level.nTiles, sizeof(level.nTiles), 1, fid);
        fwrite(&level.offset, sizeof(level.offset), 1, fid);
        fwrite(&level.scale, sizeof(level.scale), 1, fid);

        printf("\n    Level %i: % 5i tiles, offset %08X, scale: %i, %ix%i", i, level.nTiles, level.offset, level.scale, level.tileSize, level.tileSize);

    }
    tileTableStart = ftell(fid);
    fwrite(tileTable, sizeof(jnx_tile_t), tilesTotal, fid);


    // read tiles from input files
    printf("\n\nStart conversion:\n");
    for(int l = 0; l < nLevels; l++)
    {
        level_t& level = levels[l];

        std::list<file_t *>::iterator f;
        for(f = level.files.begin(); f != level.files.end(); f++)
        {
            file_t& file  = *(*f);

            uint32_t xoff = 0;
            uint32_t yoff = 0;

            uint32_t xsize = level.tileSize;
            uint32_t ysize = level.tileSize;

            while(yoff < file.height)
            {
                if(ysize > (file.height - yoff))
                {
                    ysize = file.height - yoff;
                }

                xsize = level.tileSize;
                xoff  = 0;

                while(xoff < file.width)
                {
                    if(xsize > (file.width - xoff))
                    {
                        xsize = (file.width - xoff);
                    }

                    // //
                    if(!readTile(xoff, yoff, xsize, ysize, file, tileBuf32Bit))
                    {
                        printf("\nError reading tiles from map file\n");
                        exit(-1);
                    }

                    jnx_tile_t& tile = tileTable[tileCnt++];
                    if(pj_is_latlong(file.pj))
                    {

                        double u1 = file.lon1 + xoff * file.xscale;
                        double v1 = file.lat1 + yoff * file.yscale;
                        double u2 = file.lon1 + (xoff + xsize) * file.xscale;
                        double v2 = file.lat1 + (yoff + ysize) * file.yscale;


                        tile.left   = u1 * 0x7FFFFFFF / 180;
                        tile.top    = v1 * 0x7FFFFFFF / 180;
                        tile.right  = u2 * 0x7FFFFFFF / 180;
                        tile.bottom = v2 * 0x7FFFFFFF / 180;

                    }
                    else
                    {
                        double u1 = file.xref1 + xoff * file.xscale;
                        double v1 = file.yref1 + yoff * file.yscale;
                        double u2 = file.xref1 + (xoff + xsize) * file.xscale;
                        double v2 = file.yref1 + (yoff + ysize) * file.yscale;

                        pj_transform(file.pj,wgs84,1,0,&u1,&v1,0);
                        pj_transform(file.pj,wgs84,1,0,&u2,&v2,0);

                        tile.left    = (u1 * RAD_TO_DEG) * 0x7FFFFFFF / 180;
                        tile.top     = (v1 * RAD_TO_DEG) * 0x7FFFFFFF / 180;
                        tile.right   = (u2 * RAD_TO_DEG) * 0x7FFFFFFF / 180;
                        tile.bottom  = (v2 * RAD_TO_DEG) * 0x7FFFFFFF / 180;
                    }

//                    if(tileCnt == 1020)
//                    {
//                        printf(" ");
//                    }

                    tile.width  = xsize;
                    tile.height = ysize;
                    tile.offset = ftell(fid);
                    tile.size   = writeTile(xsize, ysize, tileBuf32Bit, fid);

                    printf("\r    tile %i of %i", tileCnt, tilesTotal);
                    fflush(stdout);
                    // //
                    xoff += xsize;
                }

                yoff += ysize;
            }
        }
    }

    // terminate output file
    fwrite("BirdsEye", 8, 1, fid);

    // write final tile table
    fseek(fid, tileTableStart, SEEK_SET);
    fwrite(tileTable, sizeof(jnx_tile_t), tilesTotal, fid);
    // done
    fclose(fid);

    // clean up
    pj_free(wgs84);
    GDALDestroyDriverManager();
    printf("\n\n");
    return 0;
}
