using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Halo3Map.BLF;
using System.IO;
using Halo3Map.IO;

namespace Engineer.Controls
{
    public partial class PreviewImageViewer : UserControl
    {
        public EndianIO blfStream;

        public PreviewImageViewer(mapImage mi)
        {
            InitializeComponent();
            blfStream = mi.InputStream;
            pictureBox1.Image = mi.image;
            label1.Text = "Width " + mi.image.Width.ToString() 
                + " Height " + mi.image.Height.ToString();
        }

        private void btnExtract_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "JPEG Image|*.jpg|PNG Image|*.png";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
                if(sfd.FilterIndex == 1)
                    pictureBox1.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                else if (sfd.FilterIndex == 2)
                    pictureBox1.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Png);

                MessageBox.Show("Success");
            }
        }

        private void btnInject_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "JPEG Image|*.jpg|PNG Image|*.png";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
                BinaryReader br = new BinaryReader(fs);

                blfStream.Out.BaseStream.Position = 52;                   
                blfStream.Out.Write((int)fs.Length);

                blfStream.Out.BaseStream.Position = 68;
                byte[] temp = new byte[fs.Length];
                temp = br.ReadBytes((int)fs.Length);
                blfStream.Out.Write(temp);                
            }
        }
    }
}
