using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using C1.C1Zip;

namespace CompressFilesWithDBCSNames
{
    public partial class MainPage : UserControl
    {
        IEnumerable<FileInfo> fileInfos;
        List<string> zipFiles = new List<string>();
        
        public MainPage()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = this.comboBox1.SelectedItem as ComboBoxItem;

            if (item != null)
            {
                ZipEncoding.Encoding = EncodingEx.GetEncoding(item.Content.ToString());
            }
        }

        private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Multiselect = true 
            };

            if (dialog.ShowDialog() == true)
            {
                if (dialog.Files == null)
                {
                    return;
                }

                fileInfos = dialog.Files;
                lstFiles.ItemsSource = fileInfos.Select(fi => fi.Name);
                btnSaveZipFile.IsEnabled = fileInfos.Any();
            }
        }

        private void btnSaveZipFile_Click(object sender, RoutedEventArgs e)
        {
            var stream = new MemoryStream();
            var zip = new C1ZipFile(stream, true)
            {
                CompressionLevel = CompressionLevelEnum.BestCompression
            };

            var dialog = new SaveFileDialog 
            {
                Filter = "C1Zip Files (*.zip) | *.zip"
            };

            if (dialog.ShowDialog() == true)
            {
                foreach (var fileInfo in fileInfos)
                {
                    var fileStream = fileInfo.OpenRead();
                    zip.Entries.Add(fileStream, fileInfo.Name);
                    fileStream.Close();
                }

                var s = dialog.OpenFile();
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(s);
                s.Flush();
                s.Close();

                if (!zipFiles.Contains(dialog.SafeFileName))
                {
                    zipFiles.Add(dialog.SafeFileName);
                }

                lstZipFile.ItemsSource = null;
                lstZipFile.ItemsSource = zipFiles;
            }

            stream.Close();
        }
    }
}
