using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Diagram_API.DB
{
  public class VdpDB : DbContext
  {
    public DbSet<DB.Cycle> Cycles { get; set; }
    public VdpDB()
    {
      Database.EnsureCreated();
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseMySql("server=127.0.0.1;user=diplom;password=diplom;database=VDPCycles;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }
  }

  [Table("Cycles")]
  public class Cycle
  {
    [Column("idCycle"), Required, Key]
    public int IdCycle { get; set; }
    [Column("numVdp")]
    public int NumVdp { get; set; }
    [Column("numCycle")]
    public int NumCycle { get; set; }
    [Column("factStart")]
    public DateTime FactStart { get; set; }
    [Column("thinkEnd")]
    public DateTime ThinkEnd { get; set; }
    [Column("factEnd")]
    public DateTime FactEnd { get; set; }

  }

  public static class WorkDB
  {
    async public static Task<Cycle> GetCycle(int vdp)
    {
      var result = new Cycle();
      await Task.Run(() =>
      {
        try
        {
          using (var db = new DB.VdpDB())
          {
            var tmp = (from u in db.Cycles
                       where
                        u.NumVdp == vdp
                       orderby u.FactStart descending
                       select u).FirstOrDefault();
            result = tmp;
          }
        }
        catch (Exception e)
        {
          Console.WriteLine(e.Message);
        }
      });
      return result;
    }
  }
}
