using System;
using System.Collections;
using System.Data;
using System.Threading;
using System.IO;
using System.Data.SqlClient;
using edu.jhu.ZTestS;
using edu.jhu.Cas.Jobs;
using edu.jhu.Cas.Servers;
using edu.jhu.Cas.Users;
using edu.jhu.Cas.Util;

namespace edu.jhu.Cas.WebTest{
	class LinkTest:ZTest{
		private long wsid;
		private string srcCstring,src;
		public LinkTest(ZTestLoader tl, long Wsid, string Src, string SrcCstring):base(tl,null){
			base.Title = Src;
			base.Description = "Verifies links between title machine and the rest.";
			src = Src;
			srcCstring = SrcCstring;
			wsid = Wsid;
		}
		public override void Work(){
			DataSet ds = SqlFactory.select("select host,max(target) as target from servers group by host");
			DataSet ds2 = SqlFactory.select("select server from mydbhosts");
			
			SqlCommand com = new SqlCommand();
			com.Connection = new SqlConnection(srcCstring);
			try{
				com.Connection.Open();
			}catch{
				throw new Exception("Could not connect: "+srcCstring);
			}
			string failures = "";
			try{
				foreach(DataRow dr in ds.Tables[0].Rows){
					if(dr["target"].ToString().ToUpper().CompareTo("MYDB") == 0)continue;
					try{
						com.CommandText = "select top 0 * from ["+dr["host"]+"].master.dbo.syscolumns";
						com.ExecuteNonQuery();
					}catch{
						if(failures.Length > 1) failures+="\n";
						failures+= dr["host"].ToString();
					}
				}
				foreach(DataRow dr in ds2.Tables[0].Rows){
					try{
						com.CommandText = "select top 0 * from ["+dr["server"]+"].master.dbo.syscolumns";
						com.ExecuteNonQuery();
					}catch{
						if(failures.Length > 1) failures+="\n";
						failures+= dr["server"].ToString();
					}
				}
			}finally{
				com.Connection.Close();
                com.Connection.Dispose();
			}
			if(failures != "")
				throw new ZTestException("["+src+"] is not linked to the following machines:\n"+failures);
		}    
	}
}