using Microsoft.Win32;
using Sched.CustomClasses;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sched.CustomSubwindows
{
    /// <summary>
    /// Interaction logic for DatagridPanel.xaml
    /// </summary>
    public partial class DatagridPanel : UserControl
    {
        DataTable _DTable;
        List<string> _comboColsNames;
        ObservableCollection<ObservableCollection<object>> _comboItems;

        public DatagridPanel()
        {
            InitializeComponent();

            _DTable = new DataTable();

            BTN_Import.Click += BTN_Import_Click;
            BTN_Export.Click += BTN_Export_Click;
            DG.AutoGeneratingColumn += DG_AutoGeneratingColumn;
        }

        public void SetTableAndComboCols(DataTable dt, List<string> comboColsNames, ObservableCollection<ObservableCollection<object>> comboItems)
        {
            _DTable = dt;
            _comboColsNames = comboColsNames;
            _comboItems = comboItems;

            DG.ItemsSource = _DTable.DefaultView;
        }

        public DataTable GetTable()
        {
            return _DTable;
        }

        private void DG_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var DataG = sender as DataGrid;
            string colHeader = e.Column.Header.ToString();

            if (_comboColsNames.Contains(colHeader))
            {
                DataGridComboBoxColumn col = new DataGridComboBoxColumn();
                col.Header = e.Column.Header.ToString();
                int sourceIndex = 0;
                for (int i = 0; i < _comboColsNames.Count; i++)
                {
                    if (_comboColsNames[i] == colHeader)
                    {
                        sourceIndex = i;
                    }
                }
                col.ItemsSource = _comboItems[sourceIndex];
                col.SelectedValuePath = "Id";
                col.SelectedValueBinding = new Binding(colHeader);
                e.Column = col;
            }


            string localizedHeader = "Str_" + e.Column.Header.ToString();
            e.Column.Header = (string)Application.Current.Resources.MergedDictionaries[App._languageResDictIndex][localizedHeader];
        }
        private void BTN_Export_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "CSV (*.csv)|*.csv";
            dlg.DefaultExt = ".csv";
            if ((bool)dlg.ShowDialog())
            {
                using (StreamWriter sw = new StreamWriter(dlg.FileName, false))      //(path,append)
                {
                    try
                    {
                        string separator = ";";

                        //Columns
                        string colNames = "";
                        for (int j = 0; j < _DTable.Columns.Count; j++)
                        {
                            if (colNames.Length > 0)
                            {
                                colNames += separator;
                            }
                            colNames += _DTable.Columns[j].ColumnName;
                        }
                        sw.WriteLine(colNames);

                        //Rows
                        for (int i = 0; i < _DTable.Rows.Count; i++)
                        {
                            string fields = "";
                            for (int j = 0; j < _DTable.Columns.Count; j++)
                            {
                                if (fields.Length > 0)
                                {
                                    fields += separator;
                                }
                                fields += _DTable.Rows[i][j].ToString();
                            }
                            sw.WriteLine(fields);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

            }
        }
        private void BTN_Import_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "CSV (*.csv)|*.csv";
            dlg.DefaultExt = ".csv";
            if ((bool)dlg.ShowDialog())
            {
                using (StreamReader sr = new StreamReader(dlg.FileName))
                {
                    string separator = ";";
                    _DTable.Rows.Clear();
                    //DG.ItemsSource = null;

                    List<String> colNames = new List<string>();
                    string colNamesStr = "";
                    for (int i = 0; i < _DTable.Columns.Count; i++)
                    {
                        colNames.Add(_DTable.Columns[i].ColumnName);
                        if (colNamesStr.Length > 0)
                        {
                            colNamesStr += separator + " ";
                        }
                        colNamesStr += _DTable.Columns[i].ColumnName;
                    }

                    try
                    {
                        //Columns
                        string[] fileColNames = ((string)sr.ReadLine()).Split(separator, StringSplitOptions.None);  //
                        for (int i = 0; i < _DTable.Columns.Count; i++)
                        {
                            if ((colNames.Count != fileColNames.Length) || (fileColNames[i] != colNames[i]))
                            {
                                string msg = (string)Application.Current.Resources.MergedDictionaries[App._languageResDictIndex]["BTN_ImportCSV_header_msgEx_ColNames"];
                                throw new Exception(msg);
                            }
                        }

                        //Rows
                        string line = string.Empty;
                        string[] lineFields;
                        try
                        {
                            while ((line = (string)sr.ReadLine()) != null)
                            {
                                //Debug.WriteLine(line);
                                if (line.Length == 0)
                                { break; }

                                lineFields = line.Split(separator, StringSplitOptions.None);

                                DataRow dr = _DTable.NewRow();
                                for (int i = 0; i < colNames.Count; i++)
                                {
                                    if (_DTable.Columns[i].DataType == typeof(int))
                                    {
                                        Int32.TryParse(lineFields[i], out int val);
                                        dr[colNames[i]] = val;
                                    }
                                    else
                                    {
                                        dr[colNames[i]] = lineFields[i];
                                    }
                                }
                                _DTable.Rows.Add(dr);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "" + line);
                        }

                    }
                    catch (Exception ex)
                    {
                        string msgSeparator = (string)Application.Current.Resources.MergedDictionaries[App._languageResDictIndex]["BTN_ImportCSV_header_msgEx_Separator"];
                        string msgColNames = (string)Application.Current.Resources.MergedDictionaries[App._languageResDictIndex]["BTN_ImportCSV_header_msgEx_ColNames"];
                        MessageBox.Show(ex.Message + ".\n\n" +
                                            msgSeparator + "   " + separator + "\n" +
                                            msgColNames + ": " + colNamesStr);
                    }
                }
                DG.ItemsSource = _DTable.DefaultView;
            }
        }
    }
}
