/**********************************************************************************************
    Copyright (C) 2007 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., 59 Temple Place - Suite 330, Boston, MA 02111 USA

  Garmin and MapSource are registered trademarks or trademarks of Garmin Ltd.
  or one of its subsidiaries.

**********************************************************************************************/
#include "../Platform.h"
#include "CDevice.h"
#include <Garmin.h>

#include <cstdio>
#include <errno.h>
#include <iostream>
#include <sstream>
#include <stdio.h>

using namespace FR305;
using namespace Garmin;
using namespace std;

#if defined(HAVE_BIGENDIAN) || !defined(CAN_UNALIGNED)
#  define DBG_SHOW_WAYPOINT
#  define UNTESTED throw exce_t(errSync, "This function has not yet been tested on your platform.")
#else
#  define UNTESTED
#endif

namespace FR305
{

    class CMutexLocker
    {
        public:
            CMutexLocker(pthread_mutex_t& mutex)
            : mutex(mutex) {
                pthread_mutex_lock(&mutex);
            }

            ~CMutexLocker() {
                pthread_mutex_unlock(&mutex);
            }
        private:
            pthread_mutex_t& mutex;

    };

    void * rtThread(void *ptr) {
        cout << "start thread" << endl;
        Packet_t command;
        Packet_t response;

        CDevice * dev = (CDevice*)ptr;
        CMutexLocker lock(dev->mutex);
        try
        {
            pthread_mutex_lock(&dev->dataMutex);
            dev->_acquire();

            command.type = GUSB_APPLICATION_LAYER;
            command.id   = Pid_Command_Data;
            command.size = 2;
            *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Start_Pvt_Data);
            dev->usb->write(command);

            while(dev->doRealtimeThread) {
                pthread_mutex_unlock(&dev->dataMutex);

                if(dev->usb->read(response)) {
                    if(response.id == Pid_Pvt_Data) {
                        D800_Pvt_Data_t * srcPvt = (D800_Pvt_Data_t*)response.payload;
                        pthread_mutex_lock(&dev->dataMutex);
                        dev->PositionVelocityTime << *srcPvt;
                        pthread_mutex_unlock(&dev->dataMutex);
                    }
                }

                pthread_mutex_lock(&dev->dataMutex);
            }

            command.type = GUSB_APPLICATION_LAYER;
            command.id   = Pid_Command_Data;
            command.size = 2;
            *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Stop_Pvt_Data);
            dev->usb->write(command);

            dev->_release();
            pthread_mutex_unlock(&dev->dataMutex);
        }
        catch(exce_t& e) {
            pthread_mutex_trylock(&dev->dataMutex);
            dev->lasterror = "Realtime thread failed. " + e.msg;
            dev->doRealtimeThread = false;
            pthread_mutex_unlock(&dev->dataMutex);
        }
        cout << "stop thread" << endl;
        return 0;
    }

}


CDevice::CDevice()
:
devname("Forerunner305")
,devid(0)
,usb(0)
,doRealtimeThread(false)
,skip_if_no_signal(true)
{
    pthread_mutex_init(&dataMutex, NULL);
}


CDevice::~CDevice()
{
    //if(pScreen) delete [] pScreen;
}


const string& CDevice::getCopyright()
{
    copyright = "<h1>QLandkarte Device Driver for Garmin " + devname + "</h1>"
        "<h2>Driver I/F Ver. " INTERFACE_VERSION "</h2>"
        "<p>&#169; 2007 by Oliver Eichler (oliver.eichler@gmx.de)</p>"
        "<p>&#169; Venture HC Screenshot support by Torsten Reuschel (me@fuesika.de)</p>"
        "<p>This driver 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. </p>";
    return copyright;
}


void CDevice::_acquire()
{
    usb = new CUSB();
    usb->open();
    usb->syncup();

    //std::cout<< usb->getProductString()<<std::endl;

    if(strncmp(usb->getProductString().c_str(), devname.c_str(), devname.size()) != 0) {

        string msg = "No " + devname + " unit detected. Please retry to select other device driver.";
        //std::cerr<<msg<<std::endl;
        throw exce_t(errSync,msg);
    }
}


void CDevice::_downloadWaypoints(list<Garmin::Wpt_t>& waypoints)
{
    waypoints.clear();
    if(usb == 0) return;

    Packet_t command;
    Packet_t response;

    // ???
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = 0x1C;
    command.size = 2;
    *(uint16_t*)command.payload = 0x0000;
    usb->write(command);

    // request waypoints
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Command_Data;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Wpt);
    usb->write(command);

    while(1) {
        if(!usb->read(response)) continue;

        if(response.id == Pid_Records) {
#ifdef DBG_SHOW_WAYPOINT
            cout << "number of waypoints:" << gar_ptr_load(uint16_t, response.payload) << endl;
#endif
        }

        if(response.id == Pid_Wpt_Data) {
            D110_Wpt_t * srcWpt = (D110_Wpt_t*)response.payload;
            waypoints.push_back(Wpt_t());
            Wpt_t& tarWpt = waypoints.back();

            tarWpt << *srcWpt;
        }

        if(response.id == Pid_Xfer_Cmplt) {
            break;
        }

    }

    // request proximity waypoints
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Command_Data;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Prx);
    usb->write(command);

    while(1) {

        if(!usb->read(response)) continue;

        if(response.id == Pid_Records) {
            //TODO read data
#ifdef DBG_SHOW_WAYPOINT
            cout << "number of proximity waypoints:" << gar_ptr_load(uint16_t, response.payload) << endl;
#endif
        }

        if(response.id == Pid_Prx_Wpt_Data) {
            D110_Wpt_t * srcWpt = (D110_Wpt_t*)response.payload;
            waypoints.push_back(Wpt_t());
            Wpt_t& tarWpt = waypoints.back();

            tarWpt << *srcWpt;
        }

        if(response.id == Pid_Xfer_Cmplt) {
            break;
        }

    }

#ifdef DBG_SHOW_WAYPOINT
    list<Wpt_t>::const_iterator wpt = waypoints.begin();
    while(wpt != waypoints.end()) {
        cout << "-------------------------" << endl;
        cout << "class      " << hex << (int)wpt->wpt_class << endl;
        cout << "dspl_color " << hex << (int)wpt->dspl_color << endl;
        cout << "dspl_attr  " << hex << (int)wpt->dspl_attr << endl;
        cout << "smbl       " << dec <<(int)wpt->smbl << endl;
        cout << "lat        " << wpt->lat << endl;
        cout << "lon        " << wpt->lon << endl;
        cout << "alt        " << wpt->alt << endl;
        cout << "dpth       " << wpt->dpth << endl;
        cout << "dist       " << wpt->dist << endl;
        cout << "state      " << wpt->state << endl;
        cout << "cc         " << wpt->cc << endl;
        cout << "ete        " << wpt->ete << endl;
        cout << "temp       " << wpt->temp << endl;
        cout << "time       " << wpt->time << endl;
        cout << "category   " << wpt->wpt_cat << endl;
        cout << "ident      " << wpt->ident << endl;
        cout << "comment    " << wpt->comment << endl;
        cout << "facility   " << wpt->facility << endl;
        cout << "city       " << wpt->city << endl;
        cout << "addr       " << wpt->addr << endl;
        cout << "crossroad  " << wpt->crossroad << endl;

        ++wpt;
    }
#endif

}


void CDevice::_uploadWaypoints(std::list<Garmin::Wpt_t>& waypoints)
{
    if(usb == 0) return;
    // count number of proximity waypoints
    uint16_t prx_wpt_cnt = 0;
    list<Wpt_t>::const_iterator wpt = waypoints.begin();
    while(wpt != waypoints.end()) {
        if(wpt->dist != 1e25f) ++prx_wpt_cnt;
        ++wpt;
    }

    Packet_t command;
    Packet_t response;

    // ???
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = 0x1C;
    command.size = 2;
    *(uint16_t*)command.payload = 0x0000;
    usb->write(command);

    // transmit proximity waypoints first
    if(prx_wpt_cnt) {
        //announce number of records
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Records;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, prx_wpt_cnt);
        usb->write(command);

        wpt = waypoints.begin();
        while(wpt != waypoints.end()) {
            if(wpt->dist != 1e25f) {
                command.type = GUSB_APPLICATION_LAYER;
                command.id   = Pid_Prx_Wpt_Data;

                D110_Wpt_t * p = (D110_Wpt_t *)command.payload;
                command.size = *wpt >> *p;

                usb->write(command);

            }
            ++wpt;
        }

        //announce number of records
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Xfer_Cmplt;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Prx);
        usb->write(command);

    }

    //transmit _all_ waypoints
    //announce number of records
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Records;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, waypoints.size());
    usb->write(command);

    wpt = waypoints.begin();
    while(wpt != waypoints.end()) {

        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Wpt_Data;

        D110_Wpt_t * p = (D110_Wpt_t *)command.payload;
        command.size = *wpt >> *p;

        usb->write(command);

        ++wpt;
    }

    //announce number of records
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Xfer_Cmplt;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Wpt);
    usb->write(command);

}


void CDevice::_downloadTracks(std::list<Garmin::Track_t>& tracks)
{
    tracks.clear();
    if(usb == 0) return;

    Packet_t command;
    Packet_t response;

    // ???
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = 0x1C;
    command.size = 2;
    *(uint16_t*)command.payload = 0x0000;
    usb->write(command);

    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Command_Data;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Trk);
    usb->write(command);

    int         trackidx = 0;
    string      name;
    Track_t *   track = 0;
    int         cancel = 0;
    int         npts = 0;
    int         ntotal = 65535;
    callback(0,0,&cancel,"Download tracks ...",0);

    while(!cancel) {

        if(!usb->read(response)) continue;

                                 //read track header
        if(response.id == Pid_Trk_Hdr) {
            trackidx = 0;
            D311_Trk_Hdr_t * hdr = (D311_Trk_Hdr_t*)response.payload;
            tracks.push_back(Track_t());
            track = &tracks.back();

            *track << *hdr;
            name  = hdr->ident;
        }

        if(response.id == Pid_Records) {
            ntotal = gar_ptr_load(uint16_t, response.payload);
        }

        if(response.id == Pid_Trk_Data) {
            D304_Trk_t * data = (D304_Trk_t*)response.payload;
            TrkPt_t pt;

            pt << *data;

            if( data->lat==int32_t(2147483647)  && data->lon==int32_t(2147483647)) {
                if(!skip_if_no_signal)
                    track->track.push_back(pt);
            }
            else {
                track->track.push_back(pt);
            }

            if (++npts % 100 == 0) {
                double progress = (npts * 100.0) / ntotal;
                callback(progress,0,&cancel,0,"Transferring track data.");
            }
        }

        if(response.id == Pid_Xfer_Cmplt) {
            break;
        }
    }
    if (cancel) {
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Command_Data;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Abort_Transfer);
        usb->write(command);
    }

    callback(100,0,&cancel,0,"done");
}


void CDevice::_downloadRoutes(std::list<Garmin::Route_t>& routes)
{
    routes.clear();
    if(usb == 0) return;

    Packet_t command;
    Packet_t response;

    // ???
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = 0x1C;
    command.size = 2;
    *(uint16_t*)command.payload = 0x0000;
    usb->write(command);

    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Command_Data;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Rte);
    usb->write(command);

    int         routeidx = 0;
    string      name;
    Route_t *   route = 0;
    int         cancel = 0;
    int         npts = 0;
    int         ntotal = 65535;
    callback(0,0,&cancel,"Download routes ...",0);

    while(!cancel) {

        if(!usb->read(response)) continue;

        if(response.id == Pid_Rte_Hdr) {
            routeidx = 0;
            D202_Rte_Hdr_t * hdr = (D202_Rte_Hdr_t*)response.payload;
            routes.push_back(Route_t());
            route = &routes.back();

            *route << *hdr;
            name  = hdr->ident;
        }

        if(response.id == Pid_Records) {
            ntotal = gar_ptr_load(uint16_t, response.payload);
        }

        if(response.id == Pid_Rte_Wpt_Data) {
            D110_Wpt_t * p = (D110_Wpt_t*)response.payload;
            route->route.push_back(RtePt_t());
            RtePt_t& rtept = route->route.back();
            rtept << *p;

            if (++npts % 50 == 0) {
                double progress = (npts * 100.0) / ntotal;
                callback(progress,0,&cancel,0,"Transferring route data.");
            }
        }

        if(response.id == Pid_Rte_Link_Data) {
            D210_Rte_Link_t * l = (D210_Rte_Link_t*)response.payload;
            RtePt_t& rtept = route->route.back();
            rtept << *l;
        }

        if(response.id == Pid_Xfer_Cmplt) {
            break;
        }
    }
    if (cancel) {
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Command_Data;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Abort_Transfer);
        usb->write(command);
    }

    callback(100,0,&cancel,0,"done");
}


void CDevice::_uploadRoutes(list<Garmin::Route_t>& routes)
{
    if(usb == 0) return;

    if(devid == 0x0231) return IDeviceDefault::_uploadRoutes(routes);

    // count number of proximity waypoints

    Packet_t command;
    Packet_t response;

    // ???
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = 0x1C;
    command.size = 2;
    *(uint16_t*)command.payload = 0x0000;
    usb->write(command);

    list<Garmin::Route_t>::const_iterator route = routes.begin();
    while(route != routes.end()) {
        //announce number of records
        // D202_Rte_Hdr_t + (D110_Wpt_t + D210_Rte_Link_t) * number of route points
        uint16_t nrec = 1 + route->route.size() * 2;
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Records;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, nrec);
        usb->write(command);

        // write route header
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Rte_Hdr;
        D202_Rte_Hdr_t * r = (D202_Rte_Hdr_t *)command.payload;
        command.size = *route >> *r;
        usb->write(command);

        vector<RtePt_t>::const_iterator rtept = route->route.begin();

        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Rte_Wpt_Data;
        D110_Wpt_t * p = (D110_Wpt_t *)command.payload;
        command.size = *rtept >> *p;
        usb->write(command);

        ++rtept;

        while(rtept != route->route.end()) {

            command.type = GUSB_APPLICATION_LAYER;
            command.id   = Pid_Rte_Link_Data;
            D210_Rte_Link_t * l = (D210_Rte_Link_t *)command.payload;
            command.size = *rtept >> *l;
            usb->write(command);

            command.type = GUSB_APPLICATION_LAYER;
            command.id   = Pid_Rte_Wpt_Data;
            D110_Wpt_t * p = (D110_Wpt_t *)command.payload;
            command.size = *rtept >> *p;
            usb->write(command);

            ++rtept;
        }

        // finish block
        command.type = GUSB_APPLICATION_LAYER;
        command.id   = Pid_Xfer_Cmplt;
        command.size = 2;
        *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Rte);
        usb->write(command);
        ++route;
    }

}


void CDevice::_setRealTimeMode(bool on)
{
    CMutexLocker lock(dataMutex);
    if(doRealtimeThread == on) return;
    doRealtimeThread = on;
    if(doRealtimeThread) {
        pthread_create(&thread,NULL,rtThread, this);
    }

}


void CDevice::_getRealTimePos(Garmin::Pvt_t& pvt)
{
    if(pthread_mutex_trylock(&mutex) != EBUSY) {
        pthread_mutex_unlock(&mutex);
        throw exce_t(errRuntime,lasterror);
    }

    CMutexLocker lock(dataMutex);
    pvt = PositionVelocityTime;
}


void CDevice::_release()
{
    if(usb == 0) return;

    usb->close2();
    delete usb;
    usb = 0;
}


void CDevice::_getDevProperties(Garmin::DevProperties_t& dev_properties)
{
    if(usb == 0) return;
    Packet_t command;
    Packet_t response;

    // ask for SD Ram capacity
    command.type = GUSB_APPLICATION_LAYER;
    command.id   = Pid_Command_Data;
    command.size = 2;
    *(uint16_t*)command.payload = gar_endian(uint16_t, Cmnd_Transfer_Mem);
    usb->write(command);

    // try to read SD Ram capacity
    uint32_t memory = 0;
    uint16_t tile_limit = 0;
    while(usb->read(response)) {
        if(response.id == Pid_Capacity_Data) {
            tile_limit = gar_ptr_load(uint16_t, response.payload + 2);
            memory = gar_ptr_load(uint32_t, response.payload + 4);
        }
    }
    if(tile_limit == 0) {
        throw exce_t(errRuntime,"Failed to send map: Unable to find the tile limit of the GPS");
    }
    if(memory == 0) {
        throw exce_t(errRuntime,"Failed to send map: Unable to find the available memory of the GPS");
    }

    // add to the properties list
    properties.memory_limit = memory;
    properties.set.item.memory_limit = 1;
    properties.maps_limit = tile_limit;
    properties.set.item.maps_limit = 1;

    // return the properties
    dev_properties = properties;
}
