using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using C1.C1DataExtender;
using System.Data.OleDb;
using System.IO;

namespace ClientFilterSort
{
    partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            c1DataViewSet1.Views[0].Definition = definitionTextBox.Text;
            RefreshSortFilterUI();
            //RefreshSearchConditionsGrid();
        }

        private void RefreshSearchConditionsGrid()
        {
            searchCondGridView.Rows.Clear();
            DataGridViewComboBoxColumn colNameColumn = 
                (DataGridViewComboBoxColumn)searchCondGridView.Columns["ColumnName"];
            colNameColumn.Items.Clear();
            foreach (C1ViewColumn viewColumn in c1DataViewSet1.Views[0].Columns)
            {
                colNameColumn.Items.Add(viewColumn.ColumnName);
            }
            C1ViewColumn[] primaryKey = c1DataViewSet1.Views[0].PrimaryKey;
            pkLabel.Text = "";
            for (int i = 0; i < primaryKey.Length; i++)
            {
                if (i != 0)
                    pkLabel.Text += ", ";
                pkLabel.Text += primaryKey[i].ColumnName;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            definitionTextBox.Text = c1DataViewSet1.Views[0].Definition;
            rowOccurenceCombo.SelectedIndex = 0;
            //RefreshSearchConditionsGrid();
            RefreshSortFilterUI();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            RefreshSortFilterUI();
        }

        private void RefreshSortFilterUI()
        {
            sortTextBox.Text = c1DataViewSet1.Views[0].Sort;
            filterTextBox.Text = c1DataViewSet1.Views[0].RowFilter;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            c1DataViewSet1.Views[0].Sort = sortTextBox.Text;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            c1DataViewSet1.Views[0].RowFilter = filterTextBox.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            /// Last DataGridView row is always empty, so we don't consider it
            int searchValueCount = searchCondGridView.Rows.Count - 1;
            object[] valueArr = new object[searchValueCount];
            for (int i = 0; i < searchValueCount; i++)
            {
                /// It's not necessary to convert values from string
                /// to target type - FindByPrimaryKey will do it automatically
                valueArr[i] = searchCondGridView.Rows[i].Cells["Value"].Value;
            }
            int idx;
            try
            {
                idx = c1DataViewSet1.Views[0].FindByPrimaryKey(valueArr);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            if (idx < 0)
                MessageBox.Show("Not found");
            else
                c1DataViewSet1.Views[0].Position = idx;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            /// Last DataGridView row is always empty, so we don't consider it
            int searchValueCount = searchCondGridView.Rows.Count - 1;
            object[] valueArr = new object[searchValueCount];
            for (int i = 0; i < searchValueCount; i++)
            {
                /// It's not necessary to convert values from string
                /// to target type - Find will do it automatically
                valueArr[i] = searchCondGridView.Rows[i].Cells["Value"].Value;
            }

            DuplicateKeyOccurenceEnum duplKey = DuplicateKeyOccurenceEnum.Accidental;
            switch ((string)rowOccurenceCombo.SelectedItem)
            {
                case "First":
                    duplKey = DuplicateKeyOccurenceEnum.First;
                    break;
                case "Last":
                    duplKey = DuplicateKeyOccurenceEnum.Last;
                    break;
                case "Accidental":
                    duplKey = DuplicateKeyOccurenceEnum.Accidental;
                    break;
            }
            int idx;
            try
            {
                idx = c1DataViewSet1.Views[0].Find(valueArr, duplKey);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            /// If row is not found, the returning index is negative value
            /// which is the bitwise complement of the index of the next row 
            /// which key is larger than specified.
            if (idx < 0)
            {
                int nearestPos = ~idx;
                if (nearestPos == c1DataViewSet1.Views[0].Count)
                    nearestPos--;
                c1DataViewSet1.Views[0].Position = nearestPos;
                MessageBox.Show("Not found. Current row is set to nearest row.");
            }
            else
                c1DataViewSet1.Views[0].Position = idx;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            /// Last DataGridView row is always empty, so we don't consider it
            int searchValueCount = searchCondGridView.Rows.Count - 1;
            object[] valueArr = new object[searchValueCount];
            string[] colNameArr = new string[searchValueCount];
            for (int i = 0; i < searchValueCount; i++)
            {
                colNameArr[i] = (string)searchCondGridView.Rows[i].Cells["ColumnName"].Value;
                /// It's not necessary to convert values from string
                /// to target type - Find will do it automatically
                valueArr[i] = searchCondGridView.Rows[i].Cells["Value"].Value;
            }
            int idx;
            try
            {
                idx = c1DataViewSet1.Views[0].Find(colNameArr, valueArr);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            if (idx < 0)
                MessageBox.Show("Not found");
            else
                c1DataViewSet1.Views[0].Position = idx;
        }

        private void c1ViewSet1_ViewListChanged(object sender, C1ViewListChangedEventArgs e)
        {
            if (e.View == c1DataViewSet1.Views[0])
            {
                if (e.ListChangedType == ListChangedType.PropertyDescriptorChanged ||
                    e.ListChangedType == ListChangedType.PropertyDescriptorAdded ||
                    e.ListChangedType == ListChangedType.PropertyDescriptorDeleted)
                {
                    RefreshSearchConditionsGrid();
                }
            }
        }

        private void c1DataViewSet1_ConnectionOpening(object sender, ConnectionOpeningEventArgs e)
        {
            OleDbConnectionStringBuilder csb = new OleDbConnectionStringBuilder(e.Connection.ConnectionString);
            /// If connection string specified in application resources points to a non-existant database file
            /// then use a database from a default sample database location.
            if (!File.Exists(csb.DataSource))
            {
                csb.DataSource = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                     @"ComponentOne Samples\Common\C1NWind.mdb");
                e.Connection.ConnectionString = csb.ToString();
            }
        }
    }
}