using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using WebAPIExplorer.Data;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Provider;
using System.Reflection;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace WebAPIExplorer
{
    /// <summary>
    /// Merge Excel page 
    /// </summary>
    public sealed partial class MergeExcelPage : Page
    {        
        private List<string> MergeExcelPOSTFiles = new List<string>();
        Manage MngObj = new Manage();

        public MergeExcelPage()
        {
            this.InitializeComponent();
            SetMergeExcelPage();            
        }

        private void SetMergeExcelPage()
        {
            TxtBlkMergeExcelTitle.Text = MngObj.ResLoader.GetString("MergeExcelTitle");
            SetMergeExcelGETData();
            SetMergeExcelPOST();            
        }
        private void SetMergeExcelGETData()
        {
            Manage MngObj = new Manage();
            TxtBlkMergeExcelGETDataGETPOSTText.Text = MngObj.ResLoader.GetString("MergeExcelGETDataGETPOSTText");
            TxtBlkMergeExcelGETDataDesc.Text = MngObj.ResLoader.GetString("DescHeader");
            TxtBlkMergeExcelGETDataDescDetails.Text = MngObj.ResLoader.GetString("MergeExcelGETDataDescDetails");
            BtnMergeExcelGETData.Content = MngObj.ResLoader.GetString("BtnMergeExcel");

            TxtBlkMergeExcelGETDataParamsHeader.Text=MngObj.ResLoader.GetString("ParamHeader");
            TxtBlkMergeExcelGETDataFileName.Text = "FileName";
            TxtBlkMergeExcelGETDataFileNameDesc.Text = MngObj.ResLoader.GetString("MergeExcelGETDataFileNameDesc");
            TxtBlkMergeExcelGETDataType.Text = "Type";
            CmbMergeExcelGETDataType.DisplayMemberPath = "Text";
            CmbMergeExcelGETDataType.SelectedValuePath = "Value";
            CmbMergeExcelGETDataType.ItemsSource = MngObj.GetExcel_TypeDDList().Where(x=>(x.Text!= "json" && x.Text != "csv"));
            CmbMergeExcelGETDataType.SelectedValue = "xlsx";
            TxtBlkMergeExcelGETDataTypeDesc.Text = MngObj.ResLoader.GetString("MergeExcelGETDataTypeDesc");
            TxtBlkMergeExcelGETDataFileNamesToMerge.Text = "FileNamesToMerge";
            CmbMergeExcelGETDataFileNamesToMerge1.DisplayMemberPath = "Text";
            CmbMergeExcelGETDataFileNamesToMerge1.SelectedValuePath = "Value";
            CmbMergeExcelGETDataFileNamesToMerge1.ItemsSource = MngObj.GetExcel_WorkBookFileNameDDList();
            CmbMergeExcelGETDataFileNamesToMerge1.SelectedIndex = 0;
            CmbMergeExcelGETDataFileNamesToMerge2.DisplayMemberPath = "Text";
            CmbMergeExcelGETDataFileNamesToMerge2.SelectedValuePath = "Value";
            CmbMergeExcelGETDataFileNamesToMerge2.ItemsSource = MngObj.GetExcel_WorkBookFileNameDDList();
            CmbMergeExcelGETDataFileNamesToMerge2.SelectedIndex = 0;
            TxtBlkMergeExcelGETDataFileNamesToMergeDesc.Text = MngObj.ResLoader.GetString("MergeExcelGETDataFileNamesToMergeDesc");

            //Response Schema
            TxtBlkMergeExcelGETDataResponseSchemaHeader.Text = MngObj.ResLoader.GetString("ResponseSchemaHeader");
            TxtBoxMergeExcelGETDataResponseSchema.Text = MngObj.GetResponseSchema();

            //Result
            TxtBlkMergeExcelGETDataResultRequestUrlTitle.Text = MngObj.ResLoader.GetString("ResultRequestUrlTitle");
            TxtBlkMergeExcelGETDataResultxmlTitle.Text=MngObj.ResLoader.GetString("ResultxmlTitle");
        }

        private async void BtnMergeExcelGETData_Click(object sender, RoutedEventArgs e)
        {
            TxtBlkMergeExcelGETDataResultMsg.Text = "";
            string FullURL = App.APIBaseUri + "api/excel/merge?";
            FullURL += "FileName=" + TxtBoxMergeExcelGETDataFileName.Text.Trim();
            FullURL += "&Type=" + CmbMergeExcelGETDataType.SelectedValue.ToString();
            if (CmbMergeExcelGETDataFileNamesToMerge1.SelectedIndex > 0)
                FullURL += "&FileNamesToMerge=" + CmbMergeExcelGETDataFileNamesToMerge1.SelectedValue.ToString();
            if (CmbMergeExcelGETDataFileNamesToMerge2.SelectedIndex > 0)
                FullURL += "&FileNamesToMerge=" + CmbMergeExcelGETDataFileNamesToMerge2.SelectedValue.ToString();

            TxtBlkMergeExcelGETDataResultRequestUrl.Text = FullURL;
            StkPnlMergeExcelGETDataResultJson.Visibility = Visibility.Collapsed;
            StkPnlMergeExcelGETDataResultxml.Visibility = Visibility.Collapsed;

            if (CmbMergeExcelGETDataType.SelectedValue.ToString() != "xml")
            {
                //download excel file
                using (var client = new HttpClient())
                {
                    var fileName = string.IsNullOrEmpty(TxtBoxMergeExcelGETDataFileName.Text) ? "excel" : TxtBoxMergeExcelGETDataFileName.Text.Trim();
                    var fileFormat = string.IsNullOrEmpty(CmbMergeExcelGETDataType.SelectedValue.ToString()) ? "xlsx" : CmbMergeExcelGETDataType.SelectedValue.ToString();
                    var response = client.GetAsync(FullURL).Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        TxtBlkMergeExcelGETDataResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgInvalidResponse");
                    }
                    else
                    {
                        //download excel file
                        FileSavePicker savePicker = new FileSavePicker();
                        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                        savePicker.FileTypeChoices.Add("Excel File", new List<string>() { "." + CmbMergeExcelGETDataType.SelectedValue.ToString() });
                        savePicker.SuggestedFileName = string.IsNullOrEmpty(TxtBoxMergeExcelGETDataFileName.Text) ? "excel" : TxtBoxMergeExcelGETDataFileName.Text.Trim();
                        StorageFile file = await savePicker.PickSaveFileAsync();
                        if (file != null)
                        {
                            CachedFileManager.DeferUpdates(file);
                            await FileIO.WriteBytesAsync(file, await response.Content.ReadAsByteArrayAsync());
                            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
                            if (status == FileUpdateStatus.Complete)
                                TxtBlkMergeExcelGETDataResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgFileLocation") + file.Path;
                            else
                                TxtBlkMergeExcelGETDataResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgFileNotDownloaded");
                        }
                    }
                }
            }
            else
            {
                using (var client = new HttpClient())
                {
                    var response = client.GetAsync(FullURL).Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        TxtBlkMergeExcelGETDataResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgInvalidResponse");
                    }
                    else
                    {
                        TxtBoxMergeExcelGETDataResultxml.Text = response.Content.ReadAsStringAsync().Result.ToString();
                        StkPnlMergeExcelGETDataResultxml.Visibility = Visibility.Visible;
                    }
                }
            }
            StkPnlMergeExcelGETDataResult.Visibility = Visibility.Visible;
        }

        private void StkPnlMergeExcelGET1_Link_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (StkPnlMergeExcelGET1_Content.Visibility == Visibility.Collapsed)
                StkPnlMergeExcelGET1_Content.Visibility = Visibility.Visible;
            else
                StkPnlMergeExcelGET1_Content.Visibility = Visibility.Collapsed;
        }

        private void SetMergeExcelPOST()
        {
            Manage MngObj = new Manage();
            TxtBlkMergeExcelPOSTGETPOSTText.Text = MngObj.ResLoader.GetString("MergeExcelPOSTGETPOSTText");
            TxtBlkMergeExcelPOSTDesc.Text = MngObj.ResLoader.GetString("DescHeader");
            TxtBlkMergeExcelPOSTDescDetails.Text = MngObj.ResLoader.GetString("MergeExcelPOSTDescDetails");
            BtnMergeExcelPOST.Content = MngObj.ResLoader.GetString("BtnMergeExcel");

            TxtBlkMergeExcelPOSTParamsHeader.Text=MngObj.ResLoader.GetString("ParamHeader");
            TxtBlkMergeExcelPOSTFileName.Text = "FileName";
            TxtBlkMergeExcelPOSTFileNameDesc.Text = MngObj.ResLoader.GetString("MergeExcelPOSTFileNameDesc");
            TxtBlkMergeExcelPOSTType.Text = "Type";
            CmbMergeExcelPOSTType.DisplayMemberPath = "Text";
            CmbMergeExcelPOSTType.SelectedValuePath = "Value";
            CmbMergeExcelPOSTType.ItemsSource = MngObj.GetExcel_TypeDDList().Where(x => (x.Text != "json" && x.Text != "csv"));
            CmbMergeExcelPOSTType.SelectedValue = "xlsx";
            TxtBlkMergeExcelPOSTTypeDesc.Text = MngObj.ResLoader.GetString("MergeExcelPOSTTypeDesc");
            TxtBlkMergeExcelPOSTFilesToMerge.Text = "FilesToMerge";
            TxtBlkCtrlMergeExcelPOSTFilesToMerge.Text=MngObj.ResLoader.GetString("ResultMsgNoFileChoosenDefault");
            TxtBlkMergeExcelPOSTFilesToMergeDesc.Text = MngObj.ResLoader.GetString("MergeExcelPOSTFilesToMergeDesc");

            //Response Schema
            TxtBlkMergeExcelPOSTResponseSchemaHeader.Text = MngObj.ResLoader.GetString("ResponseSchemaHeader");
            TxtBoxMergeExcelPOSTResponseSchema.Text = MngObj.GetResponseSchema();

            //Result
            TxtBlkMergeExcelPOSTResultRequestUrlTitle.Text = MngObj.ResLoader.GetString("ResultRequestUrlTitle");            
            TxtBlkMergeExcelPOSTResultxmlTitle.Text=MngObj.ResLoader.GetString("ResultxmlTitle");            
        }

        private void BtnMergeExcelPOST_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TxtBlkMergeExcelPOSTResultMsg.Text = "";
                string FullURL = App.APIBaseUri + "api/excel/merge";

                TxtBlkMergeExcelPOSTResultRequestUrl.Text = FullURL;
                StkPnlMergeExcelPOSTResultxml.Visibility = Visibility.Collapsed;

                if (MergeExcelPOSTFiles.Count <= 0)
                {
                    TxtBlkMergeExcelPOSTResultMsg.Text = MngObj.ResLoader.GetString("MergeExcelPOSTResultMsgNoFileSelected");
                }
                else
                {
                    Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;
                    using (var client = new HttpClient())
                    using (var formData = new MultipartFormDataContent())
                    using (var fileStream = asm.GetManifestResourceStream("WebAPIExplorer.Resources." + MergeExcelPOSTFiles[0]))
                    {
                        using (var fileStream1 = asm.GetManifestResourceStream("WebAPIExplorer.Resources." + MergeExcelPOSTFiles[1]))
                        {
                            var fileName = string.IsNullOrEmpty(TxtBoxMergeExcelPOSTFileName.Text) ? "excel" : TxtBoxMergeExcelPOSTFileName.Text.Trim();
                            var fileFormat = string.IsNullOrEmpty(CmbMergeExcelPOSTType.SelectedValue.ToString()) ? "xlsx" : CmbMergeExcelPOSTType.SelectedValue.ToString();
                            formData.Add(new StringContent(fileName), "FileName");
                            formData.Add(new StringContent(fileFormat), "Type");
                            formData.Add(new StreamContent(fileStream), "FilesToMerge", MergeExcelPOSTFiles[0]);
                            formData.Add(new StreamContent(fileStream1), "FilesToMerge", MergeExcelPOSTFiles[1]);
                            var response = client.PostAsync(FullURL, formData).Result;
                            MergeExcelPOSTFiles = new List<string>();
                            TxtBlkCtrlMergeExcelPOSTFilesToMerge.Text = MngObj.ResLoader.GetString("ResultMsgNoFileChoosenDefault");

                            if (!response.IsSuccessStatusCode)
                            {
                                TxtBlkMergeExcelPOSTResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgInvalidResponse");
                            }
                            else if (CmbMergeExcelPOSTType.SelectedValue.ToString() != "xml")
                            {
                                //download excel file
                                DownloadMergeExcelPOST(response);
                            }
                            else
                            {
                                //show data in xml                            
                                TxtBoxMergeExcelPOSTResultxml.Text = response.Content.ReadAsStringAsync().Result.ToString();
                                StkPnlMergeExcelPOSTResultxml.Visibility = Visibility.Visible;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TxtBlkMergeExcelPOSTResultMsg.Text = MngObj.ResLoader.GetString("ErrorMsg") + ex.Message;
            }
            StkPnlMergeExcelPOSTResult.Visibility = Visibility.Visible;
        }

        private async void DownloadMergeExcelPOST(HttpResponseMessage response)
        {
            //download excel file
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Excel File", new List<string>() { "." + CmbMergeExcelPOSTType.SelectedValue.ToString() });
            savePicker.SuggestedFileName = string.IsNullOrEmpty(TxtBoxMergeExcelPOSTFileName.Text) ? "excel" : TxtBoxMergeExcelPOSTFileName.Text.Trim();
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteBytesAsync(file, await response.Content.ReadAsByteArrayAsync());
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
                if (status == FileUpdateStatus.Complete)
                    TxtBlkMergeExcelPOSTResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgFileLocation") + file.Path;
                else
                    TxtBlkMergeExcelPOSTResultMsg.Text = MngObj.ResLoader.GetString("ResultMsgFileNotDownloaded");
            }
        }

        private void StkPnlMergeExcelGET2_Link_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (StkPnlMergeExcelGET2_Content.Visibility == Visibility.Collapsed)
                StkPnlMergeExcelGET2_Content.Visibility = Visibility.Visible;
            else
                StkPnlMergeExcelGET2_Content.Visibility = Visibility.Collapsed;
        }

        private async void TxtBlkCtrlMergeExcelPOSTFilesToMerge_Tapped(object sender, TappedRoutedEventArgs e)
        {
            TxtBlkCtrlMergeExcelPOSTFilesToMerge.Text = MngObj.ResLoader.GetString("ResultMsgNoFileChoosenDefault");
            MergeExcelPOSTFiles = new List<string>();
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;

            picker.FileTypeFilter.Add(".xls");
            picker.FileTypeFilter.Add(".xlsx");
            picker.FileTypeFilter.Add(".csv");

            var files = await picker.PickMultipleFilesAsync();
            if (files.Count > 0)
            {
                foreach (Windows.Storage.StorageFile file in files)
                {
                    MergeExcelPOSTFiles.Add(file.Name);//MergeExcelPOSTFiles.Add(file.Path);
                }
                TxtBlkCtrlMergeExcelPOSTFilesToMerge.Text = files.Count.ToString() + " file(s) selected.";
            }
        }

    }
}


