#include <KApplication>
#include <KPushButton>
#include <KUrl>
#include <KFileDialog>

#include <QVBoxLayout>
#include <QString>
#include <QWidget>

#include <physiksvector.h>
#include <objects.h>
#include <universe.h>
#include <PhysiksDrawer.h>

using namespace Physiks;

class MyWidget : public QWidget {
  public:
    MyWidget(QWidget *parent = NULL) : QWidget(parent) {
      script_name = new QString("");
      QVBoxLayout *layout = new QVBoxLayout();
      KPushButton *opener = new KPushButton("Open");
      KPushButton *stepper = new KPushButton("Step");
      layout->addWidget(opener);
      layout->addWidget(stepper);
      setLayout(layout);

      QObject::connect(opener, SIGNAL(clicked()), this,
          SLOT(openButtonClick()));
      QObject::connect(stepper, SIGNAL(clicked()), parent, SLOT(updateGL()));

      opener->resize(200, 50);
      stepper->resize(200, 50);
    }

    /** Is this destructor even needed? I thought Qt automagically manages
      local objects */
    ~MyWidget() {
      delete script_name;
    }

    /** Adds another viewing widget to the current application. This new widget
      could act as another camera for the current Universe, or it could handle
      visualisation of a separate Universe instance. */
    void addPhysiksViewer(PhysiksDrawer *widget) {
    }

  public slots:
    /** Temporary function to handle graphical script selection */
    void openButtonClick() {
      *script_name = KFileDialog::getOpenFileName(
          KUrl(),
          "Physiks Scripts (*.py)",
          0,
          "Please select the script you would like to load");

      loadScript();
    }

  signals:
    /** Emitted upon instantiation of a Universe object */
    void newUniverse(Universe *univ);

  private:
    QString *script_name;

    /** To be implemented. It should generate a Universe with settings and
      objects as specified in the script and emit the newUniverse signal */
    void loadScript() {
      if (script_name->isEmpty()) return;
    }
};

int main(int argc, char *argv[]) {
  KApplication app();

  Universe *univ = new Universe(3, 1.0E-1);
  Vector *pos1 = new Vector(3, 0.0);
  Vector *pos2 = new Vector(3, 0.0);
  Vector *vel1 = new Vector(3, 0.0);
  Vector *vel2 = new Vector(3, 0.0);
  vel1->set(0, 1.2);
  pos2->set(2, -4.5);
  pos2->set(0, 6.3781E6);
  PhysicalObject *obj1 = new PhysicalObject(45.5, 0.0, *pos1, *vel1);
  PhysicalObject *obj2 = new PhysicalObject(5.9742E24, 0.0, *pos2, *vel2);

  univ->add_object(*obj1);
  univ->add_object(*obj2);

  MyWidget *wid = new MyWidget();
  PhysiksDrawer *drawer1 = new PhysiksDrawer(univ, wid);
  drawer1->resize(640, 640);
  wid->show();

  delete univ;
  delete pos1;
  delete pos2;
  delete vel1;
  delete vel2;
  delete obj1;
  delete obj2;
  delete wid;

  return EXIT_SUCCESS;
}
