package com.pigeon;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Exec
{
  static Logger logger = Logger.getLogger(Exec.class.getName());

  final String filepath = "./";
  public int flag;
  private String key;
  private RaceController mission;
  private int interval;
  private final int IS_START = 1;
  private final HashMap timeflag;
  AtomicReference<String> jsonString = null;
  AtomicReference<String> recString = null;
  AtomicReference<String> allJsonString = null;

  int RecNum = 0;

  int NumOfExec = 0;
  int recNum = 0;

  Statement stmt = null;
  ResultSet rs = null;

  Hashtable<String, String> ht = new Hashtable();

  Exec(String infokey, int status, RaceController task, HashMap hm, int myinterval) {
    this.key = infokey;
    this.flag = status;
    this.mission = task;
    this.timeflag = hm;
    this.interval = myinterval;
    this.ht = Numtab.getHt();
  }

  public void doit() {
    Connection con = null;

    ArrayList list = new ArrayList();
    try {
      this.RecNum = Integer.parseInt((String)this.ht.get(this.key));
    } catch (Exception e) {
      this.RecNum = 0;
    }
    String sql;
    String NumSql;
    if (!this.mission.getTbname().equals("gp_bsxx"))
    {
      try {
        sql = " select * from " + this.mission.getTbname() + "  where raceid='" + this.mission.getRaceid() + "' and ringnum <>'888888888888'" + "  ORDER BY  gradeid ASC";
        NumSql = "select count(*) as num from " + this.mission.getTbname() + "  where raceid='" + this.mission.getRaceid() + "'" + " and ringnum <>'888888888888'";

        DataBaseConnectionPool.getInstance(); con = DataBaseConnectionPool.getConnection();

        logger.info("sql=" + NumSql);
        this.stmt = con.createStatement();
        this.rs = this.stmt.executeQuery(NumSql);
        this.rs.next();
        this.recNum = this.rs.getInt("num");

        logger.info("new Num = " + this.recNum + "   old NuM= " + this.RecNum);

        if (this.recNum != this.RecNum) {
          logger.info("new records com!!");
          this.rs = this.stmt.executeQuery(sql);

          logger.info("sql=" + sql);

          int size = 0;
          ArrayList mylist = new ArrayList();
          String flag = "";
          while (this.rs.next()) {
            HashMap hm = new HashMap();

            hm.put("raceid", this.rs.getString("RaceId"));
            hm.put("pigowner", this.rs.getString("PigOwner"));
            hm.put("cotenum", this.rs.getString("CoteNum"));
            hm.put("cometime", this.rs.getString("ComeTime"));
            hm.put("distence", this.rs.getString("Distence"));
            hm.put("flag", this.rs.getString("FlAG"));
            hm.put("qh", this.rs.getString("QH"));
            hm.put("xmbh", this.rs.getString("XMBH"));
            hm.put("mm", this.rs.getString("MM"));
			hm.put("e_tag",this.rs.getString("e_tag"));
            hm.put("e_ring",this.rs.getString("e_ring"));
            hm.put("gender",this.rs.getString("gender"));

            if (this.rs.getString("FLAG").equals("0")) {
              flag = (String)this.timeflag.get("0");
            }
            if (this.rs.getString("FLAG").equals("1")) {
              flag = (String)this.timeflag.get("1");
            }
            if (this.rs.getString("FLAG").equals("2")) {
              flag = (String)this.timeflag.get("2");
            }
            if (this.rs.getString("FLAG").equals("3")) {
              flag = (String)this.timeflag.get("3");
            }
            if (this.rs.getString("FLAG").equals("4")) {
              flag = (String)this.timeflag.get("4");
            }
            if (this.rs.getString("FLAG").equals("5")) {
              flag = (String)this.timeflag.get("5");
            }
            if (this.rs.getString("FLAG").equals("6")) {
              flag = (String)this.timeflag.get("6");
            }

            hm.put("speed", this.rs.getString("Speed") + " " + flag);
            hm.put("ringnum", this.rs.getString("RingNum"));

            mylist.add(hm);
            size++;
          }
          list = mylist;
          logger.info("size = =====" + size);
        }

        this.rs.close();
        this.stmt.close();
        con.close();
      } catch (SQLException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
      } finally {
        try {
          if (this.rs != null) this.rs.close();
          if (this.stmt != null) this.stmt.close();
          if (con != null) con.close(); 
        }
        catch (Exception e) { e.printStackTrace(); }


      }

      try
      {
        logger.info("OLD__REC_Num=" + this.RecNum);
        logger.info("list length=" + list.size());

        logger.info("recNum=" + this.recNum + "   ====>old_data=" + this.RecNum);

        if (this.recNum != this.RecNum) {
          int startIndex = 0;
          int endIndex = 0;

          int step = 100;

          int total = list.size();
          int pageid = 1;

          int endIndex_v2 = 0;

          int startIndex_v2 = 0;
          int partNum_v2 = 0;
          logger.info("startIndex_v2:" + startIndex_v2 + " endIndex_v2:" + endIndex_v2 + " partNum:" + partNum_v2);

          if (total == 0) {
            String RedisKey = null;
            try {
              RedisKey = "json_" + this.key + "_1h.v2.data";
              logger.info("RedisKey:" + RedisKey);

              File delfile = new File("./" + RedisKey);
              if (delfile.exists()) delfile.delete(); 
            }
            catch (Exception e) { e.printStackTrace();
              logger.error("error from del firl:" + RedisKey);
            }

          }

          while (this.RecNum < total) {
            logger.info("RecNum=" + this.RecNum + "======");

            endIndex_v2 = endIndex_v2 + step > total ? total : endIndex_v2 + step;
            logger.info("total=" + total + "=======++++++=====");
            logger.info("startIndex_v2=" + startIndex_v2 + "==================");
            logger.info("endIndex_v2=" + endIndex_v2 + "============");

            List ll = list.subList(startIndex_v2, endIndex_v2);
            startIndex_v2 = endIndex_v2;
            partNum_v2++;
            this.RecNum = endIndex_v2;

            this.jsonString = new AtomicReference(JSONValue.toJSONString(ll));

            JSONObject obj = new JSONObject();
            obj.put("data", this.jsonString);

            obj.put("recs", Integer.valueOf(total));
            obj.put("pageid", Integer.valueOf(partNum_v2));

            String RedisKey = null;
            try {
              RedisKey = "json_" + this.key + "_" + partNum_v2 + "h.v2.data";
              logger.info("RedisKey:" + RedisKey);

              File file = new File("./" + RedisKey);

              FileOutputStream fops = new FileOutputStream(file);
              String values = "mycall(" + obj.toString().replaceAll("null", "\"\"") + ")";

              fops.write(values.getBytes("UTF-8"));
              fops.close();
            } catch (Exception e) {
              e.printStackTrace();
              logger.error("error from create file:" + RedisKey);
            }
            logger.info("new_rec_has been added the total rec_num is:" + ll.size());
          }

          this.ht.remove(this.key);

          this.ht.put(this.key, String.valueOf(total));

          logger.info("oldNum is update to:" + this.recNum);
        } else {
          logger.info("NO_records_comming !!!!,send_old_data_again !!!");
        }

        this.NumOfExec += 1;
        logger.info("NumOfExec= " + this.NumOfExec);
      } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
      }
    } else {
      try {
        sql = " select * from gp_bsxx where bs_bh='" + this.mission.getRaceid() + "'and gp_bh='" + this.mission.getQh() + "' ORDER BY  hdmc asc";
        NumSql = "select count(*) as num from  gp_bsxx where bs_bh='" + this.mission.getRaceid() + "'and gp_bh='" + this.mission.getQh() + "'";

        DataBaseConnectionPool.getInstance();
        con = DataBaseConnectionPool.getConnection();

        this.stmt = con.createStatement();
        this.rs = this.stmt.executeQuery(NumSql);
        this.rs.next();
        this.recNum = this.rs.getInt("num");
        logger.info("sql=" + NumSql);
        logger.info("new data num=" + this.recNum);

        if (this.recNum != this.RecNum) {
          logger.info("new Num = " + this.recNum + "   old NuM= " + this.RecNum);
          logger.info("new records com!!");
          this.rs = this.stmt.executeQuery(sql);
          ResultSetMetaData rsmd = this.rs.getMetaData();
          logger.info("sql=" + sql);

          ArrayList mylist = new ArrayList();
          String flag = "";
          while (this.rs.next()) {
            HashMap hm = new HashMap();

            hm.put("pigowner", this.rs.getString("gz_mc"));

            String tt = this.rs.getString("gcsj");
            String ts = tt.substring(0, tt.length() - 1);
            String thm = this.rs.getString("hm");
            ts = ts + "000".substring(0, 3 - thm.length()) + thm;
            hm.put("cometime", ts);
            hm.put("distence", this.rs.getString("bsjl"));

            if (this.rs.getString("dybz").equals("1")) {
              hm.put("ringnum", this.rs.getString("g_zhh"));
            }
            if (this.rs.getString("dybz").equals("2")) {
              hm.put("ringnum", this.rs.getString("g_dzzhh"));
            }
            if (this.rs.getString("dybz").equals("3")) {
              hm.put("ringnum", this.rs.getString("g_dm"));
            }

            hm.put("speed", this.rs.getString("fxsd"));

            hm.put("rank", this.rs.getString("hdmc"));
            hm.put("fz", this.rs.getString("g_fz"));
            hm.put("e_tag",this.rs.getString("e_tag"));
            hm.put("e_ring",this.rs.getString("e_ring"));
            hm.put("gender",this.rs.getString("gender"));

            hm.put("A", this.rs.getString("A") == null ? "" : this.rs.getString("A"));
            hm.put("B", this.rs.getString("B") == null ? "" : this.rs.getString("B"));
            hm.put("C", this.rs.getString("C") == null ? "" : this.rs.getString("C"));
            hm.put("D", this.rs.getString("D") == null ? "" : this.rs.getString("D"));
            hm.put("E", this.rs.getString("E") == null ? "" : this.rs.getString("E"));
            hm.put("F", this.rs.getString("F") == null ? "" : this.rs.getString("F"));
            hm.put("G", this.rs.getString("G") == null ? "" : this.rs.getString("G"));
            hm.put("H", this.rs.getString("H") == null ? "" : this.rs.getString("H"));
            hm.put("I", this.rs.getString("I") == null ? "" : this.rs.getString("I"));
            hm.put("J", this.rs.getString("J") == null ? "" : this.rs.getString("J"));
            hm.put("K", this.rs.getString("K") == null ? "" : this.rs.getString("K"));
            hm.put("L", this.rs.getString("L") == null ? "" : this.rs.getString("L"));
            hm.put("M", this.rs.getString("M") == null ? "" : this.rs.getString("M"));
            hm.put("N", this.rs.getString("N") == null ? "" : this.rs.getString("N"));
            hm.put("O", this.rs.getString("O") == null ? "" : this.rs.getString("O"));
            hm.put("P", this.rs.getString("P") == null ? "" : this.rs.getString("P"));
            hm.put("Q", this.rs.getString("Q") == null ? "" : this.rs.getString("Q"));
            hm.put("R", this.rs.getString("R") == null ? "" : this.rs.getString("R"));
            hm.put("S", this.rs.getString("S") == null ? "" : this.rs.getString("S"));
            hm.put("T", this.rs.getString("T") == null ? "" : this.rs.getString("T"));

            mylist.add(hm);
          }

          list = mylist;
        }

        this.rs.close();
        this.stmt.close();
        con.close();
      } catch (SQLException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
      } finally {
        try {
          if (this.rs != null) this.rs.close();
          if (this.stmt != null) this.stmt.close();
          if (con != null) con.close(); 
        }
        catch (Exception e) { e.printStackTrace(); }


      }

      try
      {
        logger.info("recNum=" + list.size() + "   ====>old_data=" + this.RecNum);

        if (this.recNum != this.RecNum) {
          int startIndex = 0;
          int endIndex = 0;
          int step = 100;
          int partNum = 0;
          int total = list.size();
          int pageid = 1;

          int endIndex_v2 = this.RecNum;
          int startIndex_v2 = (int)Math.floor(this.RecNum / 100) * 100;

          int partNum_v2 = (int)Math.floor(this.RecNum / 100);

          logger.info("startIndex_v2:" + startIndex_v2 + " endIndex_v2:" + endIndex_v2 + " partNum:" + partNum);

          if (total == 0) {
            String RedisKey = null;
            try {
              RedisKey = "json_" + this.key + "_1h.v2.data";
              logger.info("RedisKey:" + RedisKey);

              File delfile = new File("./" + RedisKey);
              if (delfile.exists()) delfile.delete(); 
            }
            catch (Exception e) { e.printStackTrace();
              logger.error("error from delfile:" + RedisKey);
            }
          }

          logger.info("totoal:" + total);

          while (endIndex_v2 < total) {
            endIndex_v2 = endIndex_v2 + step > total ? total : ((int)Math.floor(this.RecNum / 100) + 1) * 100;
            logger.info("total=" + total + "============");
            logger.info("startIndex_v2=" + startIndex_v2 + "==================");
            logger.info("endIndex_v2=" + endIndex_v2 + "============");
            List ll = list.subList(startIndex_v2, endIndex_v2);
            startIndex_v2 = endIndex_v2;
            this.RecNum = endIndex_v2;

            partNum_v2++;
            this.jsonString = new AtomicReference(JSONValue.toJSONString(ll));
            JSONObject obj = new JSONObject();
            obj.put("data", this.jsonString);
            obj.put("recs", Integer.valueOf(this.recNum));
            obj.put("pageid", Integer.valueOf(partNum_v2));

            String RedisKey = null;
            try {
              RedisKey = "json_" + this.key + "_" + partNum_v2 + "h.v2.data";
              String values = "mycall(" + obj.toString().replaceAll("null", "\"\"") + ")";
              logger.info("RedisKey:" + RedisKey);

              File file = new File("./" + RedisKey);

              FileOutputStream fops = new FileOutputStream(file);
              fops.write(values.getBytes("UTF-8"));
              fops.close();
            } catch (Exception e) {
              e.printStackTrace();
              logger.error("error from create file:" + RedisKey);
            }
            logger.info("new_rec_has been added the total rec_num is:" + ll.size());
          }

          this.allJsonString = new AtomicReference(JSONValue.toJSONString(list));
          JSONObject allobj = new JSONObject();
          allobj.put("first", "true");
          allobj.put("data", this.allJsonString);
          allobj.put("recs", Integer.valueOf(total));
          allobj.put("pageid", Integer.valueOf(Integer.valueOf((int)Math.floor(total / 100)).intValue() + 1));
          String all_filename = "json_" + this.key + "_all_h.v2.data";
          String all_values = "mycall(" + allobj.toString().replaceAll("null", "\"\"") + ")";
          File all_file = new File("./" + all_filename);

          FileOutputStream all_fops = new FileOutputStream(all_file);
          all_fops.write(all_values.getBytes("UTF-8"));
          all_fops.close();

          this.ht.remove(this.key);
          this.ht.put(this.key, String.valueOf(this.recNum));
        } else {
          logger.info("NO_records_comming !!!!,send_old_data_again !!!");
        }

        this.NumOfExec += 1;
        logger.info("NumOfExec= " + this.NumOfExec);
      } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
      }
    }
  }
}
