﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Management;

public class Prog_Compteur2
{

    public class TypesCompteurs
    {
        public const string Processor = "Processor";
        public const string NetWorkDW = "NetworkDW";
        public const string NetWorkUP = "NetworkUP";
        public const string Diskread = "Diskread";
        public const string Diskwrite = "Diskwrite";
    }

    //Compteur Systéme retourne diff valeur suivant les args
    public System.Diagnostics.PerformanceCounter perfcounter;

    public string TypePerf;
    public bool Run;
    public int ValCount;//Taille de la Liste sur laquelle est effectué la moyenne
    public float LastValue;

    private float PMoyenne;
    List<float> ValueList;


    public Prog_Compteur2(string typePerf, int countmax = 10)
    {
        //Permet de donner une valeur différente à perfcounter suivant le Case de typeperf
        this.ValueList = new List<float>();
        this.ValCount = countmax;
        this.TypePerf = typePerf;

        switch (typePerf)
        {

            case "Processor"://1
          //       Process[] currentProcesses = Process.GetProcesses();
            //     Process myProcess = currentProcesses[0];
                 this.perfcounter = new System.Diagnostics.PerformanceCounter();
                 this.perfcounter.CategoryName = "Processor";
                 this.perfcounter.CounterName = "% Processor Time";
                 this.perfcounter.InstanceName = "_Total";
                 Debug.WriteLine(this.perfcounter.InstanceName + " a été créé !!");
                break;

            case "NetworkDW"://2

                this.perfcounter = new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Received/sec", "networkcard");
                break;

            case "NetworkUP"://3

                this.perfcounter = new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", "networkcard");
                Console.WriteLine("Prog_compteur : NTWUP");
                break;

            case "DiskWrite": //4 // http://stackoverflow.com/questions/5172555/using-performancecounters-to-target-specific-drives
                this.perfcounter = new System.Diagnostics.PerformanceCounter();
                perfcounter.CategoryName = "PhysicalDisk";
                perfcounter.CounterName = "Disk Writes/sec";
                perfcounter.InstanceName = "_Total"; // Total = Monitor All HDD
                Debug.WriteLine(this.perfcounter.InstanceName + " a été créé !!");
                break; 

            case "DiskRead"://5 //http://stackoverflow.com/questions/5161803/creating-events-for-hard-disk-read-and-write
                this.perfcounter = new System.Diagnostics.PerformanceCounter();
                perfcounter.CategoryName = "PhysicalDisk";
                perfcounter.CounterName = "Disk Reads/sec";
                perfcounter.InstanceName = "_Total"; // Total = Monitor All HDD
                Debug.WriteLine(this.perfcounter.InstanceName + " a été créé !!");
                break;

            default:
                break;
        }
        this.Run = false;
    }

    private float GetNextValue()
    {
		/*
        System.Diagnostics.CounterSample sample = new CounterSample(); ;
        sample = this.perfcounter.NextSample();
        Debug.WriteLine(this.perfcounter.InstanceName + " invocation de NexValue");
        */
       
       this.LastValue = this.perfcounter.NextValue();
       Debug.WriteLine("Last Val " + this.LastValue);
            return this.LastValue;
    }
    public float Moyenne
    {

        get { return this.PMoyenne; }
        set { this.PMoyenne = value; }
    }
    /// <summary>
    /// Ajoute une valeur à la liste
    /// et recalcule la moyenne
    /// </summary>
    /// <remarks></remarks>
    public void UpdateAvgAndList()
	{
        float newvalue = GetNextValue();

        if(newvalue !=float.MaxValue)
		   // this.ValueList.Add(GetNextValue());Suppr  05/08
            this.ValueList.Add(newvalue);
        else{
            Debug.WriteLine("Impossible de lire la valeur du compteur !!!");
            return;
        }

		//Pour pouvoir requeter avec Linq il faut que ce soit un simple tableau (ou une classe)
		//jutilise Linq à cause des fonctions statistiques ici la Moyenne

		float[] SingleList = this.ValueList.ToArray();

		//IEnumerable<float> query = from perf in SingleListperf;

	//	this.Moyenne = query.Average();

		//Si le nombre max de valeurs est atteint je supprime la plus ancienne valeur mais je garde la moyenne
		if (this.ValueList.Count > this.ValCount) {
			//effacer la première valeur
			this.ValueList.RemoveAt(0);
		}

        float total = 0;
        foreach (float valeur in ValueList)
        {
            total += valeur;
        }

        this.Moyenne=total/ValueList.Count;
        Debug.WriteLine("Moyenne " + this.Moyenne);

	}

}