#include <resultset.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "ps.h"

using namespace std;

class Line{
public: vector<double> points;string name;
  Line(vector<double> p,string n){points=p;name=n;}
  bool operator< (const Line& b) const {return points<b.points;}
};

vector<double> getPoints(ResultSet res,string table,string resource,int order);
void drawLine(ostream &out,string color,string glyph,vector<double> data);
void drawRow(ostream& out,int row,vector<double> data);
vector<Line> sortLines(vector<Line> lines);
bool isValid(vector<Line>& lines,int line,int point);

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

  if(argc!=4 && argc!=9)
    {
      cout<<"Usage: "<<argv[0]<<" <filename> <ticksize> <order> [<host> <user> <pass> <table> <outputdb>]\n";
      return 1;
    }

  int ticksize=atoi(argv[2]);
  int order=atoi(argv[3]);

  string host=(argc==9?argv[4]:"127.0.0.1");
  string user=(argc==9?argv[5]:"root");
  string pass=(argc==9?argv[6]:"blah");
  string  tbl=(argc==9?argv[7]:"fleen");
  string   db=(argc==9?argv[8]:"plum_output");

  MYSQL conn=ResultSet::makeConn(host,user,pass,db);
  ResultSet res(&conn);

  res.query<<"select count(idx)/("<<order<<"/100) as success,sum(runtime_ttl)/count(idx) as avg_runtime from "<<tbl<<" where any_exceeded_inc=0 group by selectednum order by avg_runtime asc";
  res.store();

  vector<double> datax,datay;

  if(res.size()!=0)
    while(res.next())
      {
	datax.push_back(res["avg_runtime"]);
	datay.push_back(res["success"]);
      }

  if(datax.size()==0)
    {
      datax.push_back(0);
      datay.push_back(0);
    }

  ofstream out;out.open(argv[1]);
  printFile(out,ticksize,datax,datay);

}
