﻿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 ProductosCatalogo : Siegfried.Stores.BaseForm
  {
    Siegfried.Entities.Products producto = null;
    private string SearchTerm { get; set; }

    public ProductosCatalogo()
    {
      InitializeComponent();
      BodyControl = new UserControls.ProductsUC();
      OnSelectedRowOnBase += ProductosCatalogo_OnSelectedRowOnBase;
      OnSearch += ProductosCatalogo_OnSearch;
    }

    void ProductosCatalogo_OnSearch(string searchTerm)
    {
      this.SearchTerm = searchTerm;
      BindData();
    }

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

    private void BindData()
    {
      if (String.IsNullOrEmpty(this.SearchTerm)) {
        FormBindingSource.DataSource = Globals.ctx.Products.All();
      } else {
        FormBindingSource.DataSource = Globals.ctx.Products.GetBySearchTerm(this.SearchTerm);
      }

      FormBindingSource.AllowNew = true;
      FormDataGrid.DataSource = null;
      FormDataGrid.Refresh();
      FormDataGrid.DataSource = FormBindingSource;
      FormBindingNavigator.BindingSource = FormBindingSource;
    }

    void ProductosCatalogo_OnSelectedRowOnBase(object boundItem)
    {
      producto = (Siegfried.Entities.Products) boundItem;
      ((UserControls.ProductsUC) BodyControl).CurrentChanged(producto);
    }

    void FormBindingSource_CurrentChanged(object sender, EventArgs e)
    {

      if (FormBindingSource.Current != null)
        producto = ((Siegfried.Entities.Products) FormBindingSource.Current);
      else
        return;

      if (producto.Id >= 0)
        ((UserControls.ProductsUC) BodyControl).CurrentChanged(producto);
    }

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

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

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