#include "TempMonitor.h"


TempMonitor::TempMonitor( std::string ip , std::string fname ){ 
   tmp_fname = ".temp.dat";
   process_check = ".temp_process";

   std::string mk_tmpfile = "touch ";
   mk_tmpfile += process_check;
   system( mk_tmpfile.c_str() );

   ip_addrs = ip;
   out_fname = fname;

   index = 0;

   get_flag = true;
};



void TempMonitor::Get( void ){

   temp = "";

   if( get_flag ){
      std::stringstream ss;
      ss << "    # Date #       "; 
      for( int i = 0; i < ch.size();i++)ss << "#ch" << ch[i] << "  " ;
      temp = ss.str();
      temp += "\n";
      get_flag = false;
   }

   temp += GetDate();
   temp += "  ";


   //get temperature from web monitor
   for(int i = 0;i < ch.size();i++){
      temp += temp_out( ch[i] );
      temp += "  ";
   }

}


void TempMonitor::Write( void ){
    std::ofstream ofs( out_fname.c_str() , std::ios::app );
    ofs << temp << std::endl;
    ofs.close();
}


std::string TempMonitor::temp_out(int ch){
  std::stringstream ss;
  ss << ch;

  std::string shstr="w3m -dump_source \"http://";
  shstr += ip_addrs;
  shstr += "/digital.cgi?chgrp=0\" | grep \"CH ";
  shstr += ss.str();
  shstr += "<\" | cut -d \" \" -f 14 | cut -c 1-4 >> ";
  shstr += tmp_fname;

  system( shstr.c_str() );


  std::string tmp;
  std::ifstream ifs( tmp_fname.c_str() );
  ifs >> tmp;
  ifs.close();

  std::string term = "rm -f ";term += tmp_fname;
  system( term.c_str() );

  return tmp;
}


std::string TempMonitor::GetDate( void ){

   struct tm *date;
   time_t now;
   int year, month, day;
   int hour, minute, second;

   time(&now);
   date = localtime(&now);

   year = date->tm_year + 1900;
   month = date->tm_mon + 1;
   day = date->tm_mday;
   hour = date->tm_hour;
   minute = date->tm_min;
   second = date->tm_sec;

   std::stringstream ss;
   ss <<  year << "/" << month << "/" << day << "_" << hour << ":" << minute << ":" << second ;
   std::string str;ss >> str ;

   return str;
}
