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

namespace Siegfried.Stores.Catalogos
{
  public partial class KitsCatalogo : Siegfried.Stores.BaseForm
  {
    Siegfried.Entities.Kits kit = null;

    public KitsCatalogo()
    {
      InitializeComponent();
      BodyControl = new UserControls.KitsUC();
      BodyControl.Dock = DockStyle.Fill;
      OnSelectedRowOnBase += KitsCatalogo_OnSelectedRowOnBase;
    }

    private void KitsCatalogo_Load(object sender, EventArgs e)
    {
      BindData();
      FormBindingSource.CurrentChanged += FormBindingSource_CurrentChanged;
    }

    private void BindData()
    {
      FormBindingSource.DataSource = Globals.ctx.Kits.All();
      FormBindingSource.AllowNew = true;
      FormDataGrid.DataSource = null;
      FormDataGrid.Refresh();
      FormDataGrid.DataSource = FormBindingSource;
      FormBindingNavigator.BindingSource = FormBindingSource;
    }

    void KitsCatalogo_OnSelectedRowOnBase(object boundItem)
    {
      kit = (Siegfried.Entities.Kits) boundItem;
      ((UserControls.KitsUC) BodyControl).CurrentChanged(kit);
    }

    void FormBindingSource_CurrentChanged(object sender, EventArgs e)
    {

      if (FormBindingSource.Current != null)
        kit = ((Siegfried.Entities.Kits) FormBindingSource.Current);
      else
        return;

      if (kit.Id >= 0)
        ((UserControls.KitsUC) BodyControl).CurrentChanged(kit);
    }

    protected override void GuardarLogic()
    {
      kit = ((UserControls.KitsUC) BodyControl).GetChanges();
      if (kit.Id > 0) {
        Globals.ctx.Kits.Update(kit);
      } else
        Globals.ctx.Kits.Insert(kit);
      MessageBox.Show("Cambios procesados exitosamente");
      BindData();
    }

    protected override void BorrarLogic()
    {
      kit = ((UserControls.KitsUC) BodyControl).GetChanges();
      if (kit.Id > 0) {
        Globals.ctx.Kits.Delete(kit.Id);
        kit = null;
        MessageBox.Show("Cambios procesados exitosamente");
        BindData();
      }
    }

    private void KitsCatalogo_FormClosing(object sender, FormClosingEventArgs e)
    {
      Globals.ProductoActual = null;
    }
  }
}
