using System;
using System.Linq;
using System.Windows.Forms;

namespace QuickBooksContext
{
    public partial class CodeFirstDemo : Form
    {
        private QuickBooksContext context;

        public CodeFirstDemo()
        {
            InitializeComponent();
            context = new QuickBooksContext();
            context.Configuration.UseDatabaseNullSemantics = true;
        }

        private void refreshDataGrid()
        {
            var query = from line in context.Account select line;
            gridView.DataSource = query.ToList();
            gridView.Refresh();  
        }

        private void save_Information() {           
            Accounts newRecord = new Accounts();

            newRecord.TimeCreated = DateTime.Today;
            newRecord.Name = txtName.Text;
            newRecord.Type = txtType.Text;
            if(!txtBalance.Text.Equals(""))
                newRecord.Balance = Double.Parse(txtBalance.Text);
            context.Account.Add(newRecord);
            context.SaveChanges();
            refreshDataGrid();
        }

        private void update_Information() 
        {
            context.SaveChanges();
        }

        private void delete_Information(Accounts deleteAccount) {
            context.Account.Remove(deleteAccount);
            context.SaveChanges();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            save_Information();
            refreshDataGrid();
            Cursor.Current = Cursors.Default;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            update_Information();
            Cursor.Current = Cursors.Default;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            int index = gridView.CurrentRow.Index;
            String id = (String)gridView.CurrentRow.Cells[0].Value;
            Accounts order = (from o in context.Account
                              where o.ID == id
                              select o).First<Accounts>();                    
            delete_Information(order);
            refreshDataGrid();
            Cursor.Current = Cursors.Default;
        }

        private void btnImportDB_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            refreshDataGrid();
            Cursor.Current = Cursors.Default;
        }

    }
    
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new CodeFirstDemo());
        }
    }

}
