#include <string>
#include <iostream>

#include "qastroscopeVersion.hpp"
#include <qapplication.h>

#include "QTelescopeAutostar.hpp"
#include "QTelescopeAPM.hpp"
#include "QTelescopeFifo.hpp"
#include "QTelescopeMTS.hpp"
#include "QCamUtilities.hpp"
#include "PPort.hpp"

const string TelescopeTypeOption("-t");
const string DeviceOptionString("-d");

void usage(const char * progName) {
   cerr << "usage: "
        << progName
        << " <options>"<<endl;
   cerr << "\nValid options are:"<<endl;
   cerr << "  "<<TelescopeTypeOption<<" <type> to select the telescope type\n"
	<< "     type 'help' will give the list of avaible telescope type\n";
   cerr << "  "<<DeviceOptionString << " <deviceName> to choose the telescope device name.\n"
	<< "     default is /dev/ttyS0.\n";
   cerr << endl;
}

int main(int argc, char ** argv) {

   string telescopeType;
   string deviceName("/dev/ttyS0");

   cout << qastroscopeName << " " << qastroScopeVersion
        << " (build "<<qastroscopeBuild<<")"<<endl;
   cout << "* " << qastroscopeWeb << endl;
   cout << "* " << qastroscopeMail << endl;
   cout << endl;

   QCamUtilities::computePathName(argv[0]);
   
   QApplication app(argc,argv);

   for (int i=1;i <argc;++i) {
      if ( TelescopeTypeOption == argv[i]) {
         ++i;
         if (i==argc) {
            usage(argv[0]);
            exit(1);
         }
	 telescopeType=argv[i];
      } else if ( DeviceOptionString == argv[i]) {
	 deviceName=argv[++i];
      } else {
         usage(argv[0]);
         exit(1);
      }
   }

   if (telescopeType.length()==0) {
      usage(argv[0]);
      exit(1);
   }

   if (telescopeType == "help") {
      cout << "supported scopes:\n"
           << "* autostar\n"
           << "* apm\n"
           << "* mts\n"
           << "* fifo\n";
      exit(0);
   }

   QTelescope * t;
   if (telescopeType=="autostar") {
      t= new QTelescopeAutostar(deviceName.c_str());
   } else if (telescopeType=="fifo") {
      t= new QTelescopeFifo(deviceName.c_str());
   } else if (telescopeType=="apm") {
      t= new QTelescopeAPM(PPort::getPPort(0x378));
   } else if (telescopeType=="mts") {
     t= new QTelescopeMTS(deviceName.c_str());
   } else {
      cerr << "unsupported telescope type "
           <<"'"<<telescopeType<<"'"<<endl;
       usage(argv[0]);
      exit(1);
   }
   t->buildGUI();
   return app.exec();
}

