﻿/////////////////////////////////////////////////////////////////////////
// ReadWriteBytes.cs - demonstrate chunking of files                   //
//                                                                     //
// Jim Fawcett, CSE681 - Software Modeling and Analysis, Fall 2008     //
/////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;

namespace Chunking
{
  class chunker
  {
    private FileStream fs_in;
    private FileStream fs_out;
    Byte[] block_;
    int bytesRead;
    static int blockCount = 0;

    public chunker(int BlockSize)
    {
      block_ = new Byte[BlockSize];
    }
    public void Source(string srcName)
    {
      if(!File.Exists(srcName))
        throw new Exception("can't find " + srcName);
      fs_in = File.OpenRead(srcName);
    }
    public void Destin(string dstName)
    {
      if(File.Exists(dstName))
      {
        DialogResult dr = 
          MessageBox.Show(
            "Overwrite " + dstName + " ?",
            "Destination File",
            MessageBoxButtons.YesNo
          );
        if(dr == DialogResult.Yes)
          File.Delete(dstName);
        else 
          throw new Exception("can't overwrite " + dstName);
      }
      fs_out = File.Create(dstName);
    }
    public int Read()
    {
      return bytesRead =  fs_in.Read(block_, 0, block_.Length);
    }
    public void Write()
    {
      fs_out.Write(block_, 0, bytesRead);
    }
    public void Close()
    {
      fs_in.Close();
      fs_out.Close();
    }
    public void ShowBlock()
    {
      // assumes block consists of ascii text, which may not be true
      UTF8Encoding enc = new UTF8Encoding();
      string temp = enc.GetString(block_, 0, bytesRead);
      Console.Write(temp);
    }
  }
  class ReadWriteBytes
  {
    static void Main(string[] args)
    {
      Console.Write("\n  Demonstrating File Chunking");
      Console.Write("\n =============================\n");
      try
      {
        string src_file = "../../ReadWriteBytes.cs";
        string dst_file = "temp.txt";
        chunker chkr = new chunker(1024);
        chkr.Source(src_file);
        chkr.Destin(dst_file);
        int size, count=0;
        while ((size = chkr.Read()) > 0)
        {
          Console.Write("\n  chunk #{0}: size = {1}", count++, size);
          // chkr.ShowBlock();
          chkr.Write();
        }
        chkr.Close();
        string dir = Environment.CurrentDirectory;
        Console.Write("\n\n  contents found in {0}\n\n", dir + '\\' + dst_file);
      }
      catch (Exception ex)
      {
        Console.Write("\n  {0}\n\n", ex.Message);
      }
    }
  }
}
