using System;
using System.Xml;
using System.Xml.Serialization;
using System.Data;
using net.ivoa.VOTable;
using System.IO;
using System.Text.RegularExpressions;
using net.ivoa.adql;
using System.Data.SqlClient;

using net.ivoa.data;



namespace edu.jhu.Cas.Util{
    public abstract class WholeTableUpload {
        //uses transaction/coinnection from command
        public static void LoadDataWrapper(DataWrapper dw, SqlCommand command, string tableName, bool newTable) {
            SqlCommand com = new SqlCommand();
            SqlCommand c2 = new SqlCommand();

            if (command.Transaction != null) {
                com.Transaction = command.Transaction;
                c2.Transaction = command.Transaction;
            }
            com.Connection = command.Connection;
            c2.Connection = command.Connection;
            string qry = "CREATE TABLE " + tableName + " (";
            for (int x = 0; x < dw.ColCount; x++) {
                qry += "[" + dw.ColName(x) + "] " + VOTableUtil.GetSqlDBType(dw.MSColType(x)).ToString();
                if (x < (dw.ColCount - 1))
                    qry += ",";
            }
            qry += ")";
            com.CommandText = qry;
            if (newTable) {
                com.ExecuteNonQuery();
            }
            qry = "";
            for (int y = 0; y < dw.RowCount; y++) {
                qry += "insert into " + tableName + " values(";
                for (int x = 0; x < dw.ColCount; x++) {
                    if (dw.MSColType(x) == typeof(string)
                        || dw.MSColType(x) == typeof(char[]) ||
                        dw.MSColType(x) == typeof(DateTime)) {
                        qry += "'" + dw[y, x].ToString() + "'";
                    }
                    else {
                        if (dw[y, x] == null || dw[y, x] == DBNull.Value)
                            qry += "null";
                        else
                            qry += dw[y, x].ToString();
                    }
                    if (x < (dw.ColCount - 1))
                        qry += ",";
                }
                qry += ") ";
                c2.CommandText = qry;
                c2.ExecuteNonQuery();
                qry = "";
            }
        }
		
    }
}
