// See https://aka.ms/new-console-template for more information

using Microsoft.VisualBasic.FileIO;
using System;
using System.Data.OleDb;
using System.Diagnostics;

class Programar_download
{
    static void Main()
    {
        //Ler_csv(@"X:\Back\Carteira x.x\Codigo\Cadastro_envios.csv");
        criar_arq_med("ESACLNENTR101 (L)", new DateTime(2021, 12, 01), new DateTime(2021, 12, 31));
        Console.WriteLine("Programa encerrado.");
        return;
        Environment.Exit(0);
    }
    
    static void criar_arq_med(string Cod_SCDE, DateTime data_ini, DateTime data_fim)
    {
        string strSQL;
        string tex_arq_med;
        string cam_saida;

        cam_saida = @"X:\Back\Carteira x.x\Codigo\";
        cam_saida += Cod_SCDE; //+ "_" + data_ini + "_" + data_fim;
        //cam_saida += ".csv";
        cam_saida += ".xlsx";
        tex_arq_med = "Codigo;Data;Hora;Ativa_Consumo;Ativa_Geracao;Reativa_Consumo;Reativa_Geracao;Qualidade;Origem;Mes_ref" + "\n";

        strSQL = "SELECT *  ";//WHERE Cliente ALike " + "\"" + "%" + nome_entrada + "%" + "\"";
        strSQL += " FROM SCDE_medicoes";
        strSQL += " WHERE Cod_SCDE = " + "\"" + Cod_SCDE + "\"";
        strSQL += " AND Data >= " + data_ini.ToOADate();
        strSQL += " AND Data <= " + data_fim.ToOADate();
        strSQL += " ORDER BY Cod_SCDE, Data, Hora";

        OleDbConnection conn = new("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=X:/Middle/Informativo Setorial/Modelo Word/BD_SCDE.accdb;Jet OLEDB:Database Password=gds21");
        conn.Open();
        OleDbCommand tbEmpresas = new(strSQL, conn);
        OleDbDataReader reader = tbEmpresas.ExecuteReader();

        while (reader.Read())
        {
            tex_arq_med += reader["Cod_SCDE"].ToString() + ";";
            tex_arq_med += reader["Data"].ToString() + ";";
            tex_arq_med += reader["Hora"].ToString() + ";";
            tex_arq_med += reader["Ativa_C_kWh"] + ";";
            tex_arq_med += reader["Ativa_G_kWh"] + ";";
            tex_arq_med += reader["Reativa_C_kWh"] + ";";
            tex_arq_med += reader["Reativa_G_kWh"] + ";";
            tex_arq_med += reader["Qualidade"].ToString() + ";";
            tex_arq_med += reader["Origem"].ToString() + ";";
            tex_arq_med += reader["Mes_ref"].ToString() + ";";
            tex_arq_med += "\n";
        }
        conn.Close();
        File.WriteAllText(cam_saida, tex_arq_med);

    }
    
    static void Ler_csv(string caminho)
    {
        string dia_sem;
        string texto_saida = "";
        string mes;
        int dia_int;
        int hoje_dia;
        string[] fields;

        using (TextFieldParser parser = new TextFieldParser(caminho))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(";");
            while (!parser.EndOfData)
            {
                fields = parser.ReadFields();
                switch (fields[1])
                {
                    case "d":
                        Console.WriteLine(String.Format("Cliente {0} tera envio diario", fields[0]));
                        fields[3] = DateTime.Now.ToString();
                        break;
                    case "m":
                        Console.WriteLine(String.Format("Cliente {0} tera envio mensal", fields[0]));
                        break;
                    default:
                        if (fields[1].Substring(0, 1) == "s")
                        { 
                            dia_sem = fields[1].Substring(fields[1].Length - 1, 1);
                            Int32.TryParse(dia_sem, out dia_int);
                            hoje_dia = ((int)DateTime.Today.DayOfWeek == 0) ? 7 : (int)DateTime.Today.DayOfWeek;
                            mes = DateTime.Today.ToString("yyMM");
                            Console.WriteLine(String.Format("Cliente {0} tera envio semanal no dia {1}, hoje e dia {2} do mes {3}", fields[0], dia_sem, hoje_dia, mes));                            
                        }
                        break;
                }
                foreach (string field in fields)
                {
                    texto_saida += field + ";";
                }
                texto_saida += "\n";
            }            
        }
        File.WriteAllText(caminho, texto_saida);
        return;
    }
}

/*
 Frequencias de envio:
    d - diario
    sx - semanal no dia x
    m - mensal
Tipo de envio
    h - horario
    d - diario
    5 - 5 minutos
 */