using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VisualCron;
using VisualCronAPI;

public partial class _Default : System.Web.UI.Page
{
    private Server serveur = new Server();
    private List<JobClass> allJobs = null;
    private List<JobClass> displayJobs = null;
    //private List<JobClass> displayGroups = null;
    private List<string> serveurs = null;
    private DataSet dsGroupes = new DataSet();
    private DataTable dtGrp = new DataTable();
    private Boolean listFailed = false;
    private Boolean listSearched = false;
    private string toSearch = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        string temporaire = Application["serveurs"].ToString();
        string selectedServeur = Session["myServer"].ToString();
        PopulateAllJobs(selectedServeur);
        if (!IsPostBack)
        {
            serveurs = temporaire.Split(';').ToList();
            foreach (string strTemp in serveurs)
            {
                lstbServeur.Items.Add(strTemp.ToString());
            }
            lstbServeur.SelectedIndex = 0;
            selectedServeur = serveurs[0];
            dtGrp = GetGroups();
            lvGroups.DataSource = dtGrp;
            lvGroups.DataBind();
        }

    }

    public void PopulateAllJobs(string serverName)
    {
        VisualCronAPI.Client client = new Client();
        VisualCronAPI.Connection connexion = new Connection();

        connexion.Address = serverName;
        connexion.ConnectionType = Connection.ConnectionT.Remote;
        connexion.UseADLogon = true;
        try
        {
            serveur = client.Connect(connexion, true);

        }
        catch (Exception e)
        {

            lblError.Text = serverName + " connexion error \n" + e.Message;
            lblError.Visible = true;
            allJobs = null;
            //throw;
        }
        if (serveur.Connected)
        {
            lblError.Visible = false;
            lblError.Text = "";
            allJobs = serveur.Jobs.GetAll();
            client.Disconnect(serveur);
        }
        //else
        //{
        //    lblError.Text = serverName + " is not connected";
        //    allJobs = null;
        //}
    }

    protected void lstbServeurSelectionChange(object sender, EventArgs e)
    {
        Session["myServer"] = lstbServeur.SelectedItem.ToString();
        string temporaire = lstbServeur.SelectedItem.ToString();
        PopulateAllJobs(temporaire);
        Label1.Text = "";
        TextBox1.Text = "";
        dtGrp = GetGroups();
        lvGroups.DataSource = dtGrp;
        lvGroups.DataBind();
    }
    protected void btnFailed_Click(object sender, EventArgs e)
    {
        listFailed = true;
        dtGrp = GetGroups();
        lvGroups.DataSource = dtGrp;
        lvGroups.DataBind();
        listFailed = false;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Response.Redirect("~/SearchFailedResult.aspx");
        listSearched = true;
        toSearch = tbxSearchText.Text;
        dtGrp = GetGroups();
        lvGroups.DataSource = dtGrp;
        lvGroups.DataBind();
        listSearched = false;
    }
    protected DataTable GetGroups()
    {
        if (allJobs == null)
        {
            //displayGroups = null;
            return null;
        }
        else
        {
            DataTable dtGroupes = new DataTable();

            dtGroupes.Columns.Add("Groupe", typeof(string));

            IList<string> groupes = (from job in allJobs
                                     orderby job.Group
                                     select job.Group).Distinct().ToList();

            foreach (string gr in groupes)
            {
                TextBox2.Text += gr + "\r\n";
                if (listFailed)
                {
                    displayJobs = (from job in allJobs
                                   where (job.Group.Equals(gr) && job.Stats.Status != JobStatsClass.StatusT.Running)
                                   orderby job.Name
                                   from taches in job.Tasks
                                   where taches.Stats.Result != "Success"
                                   select job).Distinct().ToList();
                    if (displayJobs.Count != 0)
                    {
                        dtGroupes.Rows.Add(gr);
                    }
                }
                else
                {
                    if (listSearched)
                    {
                        displayJobs = (from job in allJobs
                                       where (job.Group.Equals(gr) && job.Name.ToUpper().Contains(toSearch.ToUpper()))
                                       orderby job.Name
                                       select job).ToList();
                        if (displayJobs.Count != 0)
                        {
                            dtGroupes.Rows.Add(gr);
                        }
                    }
                    else
                    {
                        dtGroupes.Rows.Add(gr);
                    }
                }
            }
            return dtGroupes;
        }
    }

    public string GetTaskResult(JobClass job)
    {
        string result;
        result = "~/images/ProgressSuccess.ico";
        foreach (TaskClass tache in job.Tasks)
        {
            if (tache.Stats.Result != "Success")
            {
                result = "~/images/ProgressError.ico";
                break;
            }
        }
        return result;
    }

    public string GetStatsActive(JobClass job)
    {
        string result;
        if (job.Stats.Active)
        {
            result = "~/images/icon_active.png";

        }
        else
        {
            result = "~/images/unpublished_inactive_icon.gif";

        }
        return result;
    }

    protected void linkJobTasks_Click(object sender, EventArgs e)
    {
        foreach (JobClass job in allJobs)
        {
            if (job.Name == ((LinkButton)sender).Text)
            {
                if (job.Stats.Status != JobStatsClass.StatusT.Running)
                {
                    string monServeur = Session["myServer"].ToString();
                    string monTexte = "";
                    //string monTexte2 = "";
                    VisualCronAPI.Client client = new Client();
                    VisualCronAPI.Connection connexion = new Connection();

                    connexion.Address = monServeur;
                    connexion.ConnectionType = Connection.ConnectionT.Remote;
                    connexion.UseADLogon = true;

                    serveur = client.Connect(connexion, true);

                    TextBox1.Visible = true;
                    Int32 nbTache = 0;
                    Label1.Text = job.Name;
                    Label1.ForeColor = Color.Red;
                    TextBox1.Text = "";
                    foreach (TaskClass tache in job.Tasks)
                    {
                        nbTache++;
                        TextBox1.Text += "\nTask " + nbTache.ToString() + " : " + tache.Name;
                        if (tache.Stats.Result != "Success")
                        {
                            TextBox1.Text += "\n\nResult = " + tache.Stats.Result;
                        }
                        //TextBox1.Text += "\n\nNumber of characters in StandardOutput = " + tache.Stats.StandardOutput.Length.ToString();
                        //TextBox1.Text += "\n\nStandard Output : " + job.get_Task(tache.Id.ToString());
                        TextBox1.Text += "\n\nOutput\n------";
                        monTexte = serveur.Jobs.Tasks.GetOutputString(OutputInfoClass.OutputT.StandardOutput, tache.JobId, tache.Id, true).ToString();
                        //TextBox1.Text += "\n" + Encoding.ASCII.GetString(tache.Stats.StandardOutput);
                        TextBox1.Text += serveur.Jobs.Tasks.GetOutputString(OutputInfoClass.OutputT.StandardOutput, tache.JobId, tache.Id, true).ToString();
                        //tache.GetOutputString(OutputType, tache.JobId, tache.Id, True);
                        TextBox1.Text += "\n---------------------------------------------------------";

                    }
                    serveur.Disconnect();
                }
                else
                {
                    Label1.Text = job.Name + " is running!";
                    Label1.ForeColor = Color.Red;
                }
                break;
            }
        }
        TextBox1.Focus();
    }

    public string CvtSecondsToTime(JobClass job)
    {
        TimeSpan t = TimeSpan.FromSeconds(job.Stats.ExecutionTime);
        string answer = string.Format("{0:D2}:{1:D2}:{2:D2},{3:D3}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
        return answer;
    }

    protected void lvGroupsItemDataBound(object sender, ListViewItemEventArgs e)
    {
        string groupe = "";
        displayJobs = null;
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            DataRowView groupes = (DataRowView)dataItem.DataItem;
            //groupe = (string)groupes.Row.ItemArray.GetValue((int)dataItem.DataItemIndex);
            groupe = (string)groupes.Row.ItemArray.GetValue(0);
            if (listFailed)
            {
                displayJobs = (from job in allJobs
                               where (job.Group.Equals(groupe) && job.Stats.Status != JobStatsClass.StatusT.Running)
                               orderby job.Name
                               from taches in job.Tasks
                               where taches.Stats.Result != "Success"
                               select job).Distinct().ToList();

            }
            else
            {
                if (listSearched)
                {
                    displayJobs = (from job in allJobs
                                   where (job.Group.Equals(groupe) && job.Name.ToUpper().Contains(toSearch.ToUpper()))
                                   orderby job.Name
                                   select job).ToList();
                }
                else
                {
                    displayJobs = (from job in allJobs
                                   where (job.Group.Equals(groupe))
                                   orderby job.Name
                                   select job).ToList();

                }
            }
            ListView lvJobs = (ListView)dataItem.FindControl("lvJobs");
            lvJobs.DataSource = displayJobs;
            lvJobs.DataBind();
        }
    }
}