using Ionic.Zip;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;

namespace CXMLDecompiler
{
    class GimConv
    {

        public static string GIMCONV_FOLDER = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "GimConv");

        static WebClient wc = new WebClient();
        static bool DownloadCompleted = true;

        public static void ConvertGimToPng(string inputGim, string outputGim)
        {
            if (HasGimConv())
            {
                if (!Path.IsPathRooted(inputGim))
                    inputGim = Path.Combine(Environment.CurrentDirectory, inputGim);

                if (!Path.IsPathRooted(outputGim))
                    outputGim = Path.Combine(Environment.CurrentDirectory, outputGim);

                Console.WriteLine("Decoding GIM.");
                Process Proc = new Process();
                Proc.StartInfo.FileName = Path.Combine(GIMCONV_FOLDER, "GimConv.exe");
                Proc.StartInfo.Arguments = "\"" + inputGim + "\" -o \"" + outputGim  + "\"";
                Proc.StartInfo.RedirectStandardOutput = true;
                Proc.StartInfo.RedirectStandardError = true;
                Proc.StartInfo.UseShellExecute = false;
                Proc.Start();
                Proc.WaitForExit();
                Console.Write(Proc.StandardOutput.ReadToEnd());
            }
        }
        public static bool HasGimConv()
        {
            return File.Exists(Path.Combine(GIMCONV_FOLDER, "GimConv.exe"));
        }
        public static void  DownloadGimConv()
        {
            wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
            wc.DownloadDataCompleted += Wc_DownloadDataCompleted;
            wc.DownloadDataAsync(new Uri("http://e1.dl.playstation.net/e1/downloads/ps3/themes/370/PS3_Custom_Theme_v200.zip")); // Thanks Sony :3
            while (wc.IsBusy || !DownloadCompleted) { };
        }

        private static void Wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            Console.Write("\r\n");
            MemoryStream zipStream = new MemoryStream(e.Result);
            ZipFile zip = ZipFile.Read(zipStream);
            foreach(ZipEntry zEntry in zip.Entries) // Read downloaded zip and extract stuff relating to GimConv .
            {
                string filename = Path.GetFileName(zEntry.FileName);
                if (filename == "msvcp71.dll" || filename == "msvcr71.dll" || zEntry.FileName.Contains("GimConv")) // if it is a required DLL or inside the GimConv folder
                {
                    string outputFilename = zEntry.FileName;
                    if (outputFilename.Contains("GimConv")) // if the filename is inside the GimConv folder
                        outputFilename = outputFilename.Substring(outputFilename.IndexOf("GimConv") + "GimConv".Length + 1); // Extract filename after the "GimConv/" part
                    else
                        outputFilename = Path.GetFileName(outputFilename);

                    outputFilename = outputFilename.Replace("/", "\\");
                    outputFilename = Path.Combine(GIMCONV_FOLDER, outputFilename); // set output path to GimConv folder
                    Console.WriteLine("Extracting: " + outputFilename);

                    // If folder is directory, create it
                    if (zEntry.IsDirectory)
                    {
                        Directory.CreateDirectory(outputFilename);
                        continue;
                    }

                    // Extract the file to output path
                    FileStream fs = File.Open(outputFilename, FileMode.CreateNew, FileAccess.ReadWrite);
                    zEntry.Extract(fs);
                    fs.Close();
                }
            }
            zip.Dispose();
            zipStream.Dispose();

            File.AppendAllText(Path.Combine(GIMCONV_FOLDER, "GimConv.cfg"), "option -psvrgba8888 {\r\n    format_endian = little\r\n    format_style = psp\r\n    image_format = rgba8888\r\n    pixel_order = normal\r\n    pixel_channel = rgba\r\n    limit_image_width = 4096\r\n    limit_image_height = 4096\r\n}\r\noption -psvindex4 {\r\n    format_endian = little\r\n    format_style = psp\r\n    image_format = index4\r\n    pixel_order = normal\r\n    pixel_channel = rgba\r\n    limit_image_width = 4096\r\n    limit_image_height = 4096\r\n}\r\noption -psvindex8 {\r\n    format_endian = little\r\n    format_style = psp\r\n    image_format = index8\r\n    pixel_order = normal\r\n    pixel_channel = rgba\r\n    limit_image_width = 4096\r\n    limit_image_height = 4096\r\n}");
            DownloadCompleted = true;
        }

        private static void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            DownloadCompleted = false;
            Console.Write("\rDownloading GimConv Directly from Sony " + e.BytesReceived + "/" + e.TotalBytesToReceive + " - " + e.ProgressPercentage.ToString() + "%");
        }
    }
}
