﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Siegfried.Stores.UserControls
{
  public partial class KitsPricesUC : UserControl
  {
    public KitsPricesUC()
    {
      InitializeComponent();
    }

    private void KitsPricesUC_Load(object sender, EventArgs e)
    {
      RebindGrid();

      var niveles = Globals.ctx.PriceLevels.All();
      BindingSource nivelesSource = new BindingSource();
      nivelesSource.DataSource = niveles;
      cbxNivelDePrecio.DataSource = nivelesSource;
      cbxNivelDePrecio.ValueMember = "Id";
      cbxNivelDePrecio.DisplayMember = "Name";
    }

    private void RebindGrid()
    {
      dgvPrecios.DataSource = null;

      int kitId = Globals.KitActual.Id;
      var precios = Globals.ctx.vwKitsPrices.Query<Siegfried.Entities.vwKitsPrices>("SELECT * FROM vwKitsPrices WHERE Id=@KitId", new { KitId = kitId })
        .Select(s => new { Id = s.PriceLevelId, NivelDePrecio = s.Name, Precio = s.Price }).ToList();
      dgvPrecios.DataSource = precios;
    }

    private void dgvPrecios_SelectionChanged(object sender, EventArgs e)
    {
      if (dgvPrecios.SelectedRows.Count > 0) {
        int priceLevelId = System.Convert.ToInt32(dgvPrecios.SelectedRows[0].Cells[0].Value.ToString());
        string priceValue  = dgvPrecios.SelectedRows[0].Cells[2].Value.ToString();
        cbxNivelDePrecio.SelectedValue = priceLevelId;
        txtPrecio.Text = priceValue;
      }
    }

    private void btnAgregarPrecio_Click(object sender, EventArgs e)
    {
      BorrarPrecioExistente();
      Siegfried.Entities.KitsPrices newPrice = new Siegfried.Entities.KitsPrices();
      newPrice.KitId = Globals.KitActual.Id;
      newPrice.PriceLevelId = System.Convert.ToInt32(cbxNivelDePrecio.SelectedValue.ToString());
      newPrice.Price = System.Convert.ToDecimal(txtPrecio.Text);
      Globals.ctx.KitsPrices.Insert(newPrice);

      RebindGrid();
    }

    private void btnBorrarPrecio_Click(object sender, EventArgs e)
    {
      BorrarPrecioExistente();

      RebindGrid();
    }

    private void BorrarPrecioExistente()
    {
      int kitId = Globals.KitActual.Id;
      int priceLevelId = System.Convert.ToInt32(cbxNivelDePrecio.SelectedValue.ToString());
      var precios = Globals.ctx.KitsPrices.Query<Siegfried.Entities.KitsPrices>(
        "Select * from KitsPrices Where KitId=@KitId and PriceLevelId=@PriceLevelId",
        new { KitId = kitId, PriceLevelId = priceLevelId }).ToList();
      foreach (Siegfried.Entities.KitsPrices precio in precios)
        Globals.ctx.KitsPrices.Delete(precio.Id);
    }
  }
}
