using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Jdas_Mbic
{
    public partial class MBIC_DownLoadWnc : Form
    {
        public MBIC_DownLoadWnc()
        {
            InitializeComponent();
        }
        public JdasMbic main;
        const string MBIC_HeaderName = "JT-NRDAS ";

        byte[] MBIC_Add_BootLoader_DataArray = new byte[128];
        public byte[] MBIC_BootLoader_DataArray;
        Bluecell_BootProtocol bluecell_BootProtocol = new Bluecell_BootProtocol();
        byte[] MBIC_BootLoaderData;

        private void button_Test_Click(object sender, EventArgs e)
        {
           
        }
        OpenFileDialog Mbic_ofd = new OpenFileDialog();
        string fileName; //= Mbic_ofd.SafeFileName;
        string fileFullName;// = Mbic_ofd.FileName;
        private void button_FileOpen_Click(object sender, EventArgs e)
        {






           
            //파일오픈창 생성 및 설정
            Mbic_ofd.Title = "업데이터 파일 탐색기";
            Mbic_ofd.FileName = "*.mbc";
            Mbic_ofd.Filter = "mbc 파일 (*.mbc) | *.mbc;|binary 파일 (*.binary,*.bin,) | *.binary;, *.bin;|  모든 파일 (*.*) | *.*";
            
            //string s3 = DateTime.Now.ToString("yyMMdd");

            //파일 오픈창 로드
            DialogResult dr = Mbic_ofd.ShowDialog();

            //OK버튼 클릭시
            if (dr == DialogResult.OK)
            {
                //File명과 확장자를 가지고 온다.
                fileName = Mbic_ofd.SafeFileName;

                //File경로와 File명을 모두 가지고 온다.
                fileFullName = Mbic_ofd.FileName;

                //File경로만 가지고 온다.
                string filePath = fileFullName.Replace(fileName, "");
                //this.serial.debug_hextoasciiConvert();

                //출력 예제용 로직
                //  label1.Text = "File Name  : " + fileName;
                // label2.Text = "Full Name  : " + fileFullName;
                // label3.Text = "File Path  : " + filePath;`
                //File경로 + 파일명 리턴
                //JT-NRDAS 
                textBox_FilePath.Text = fileName;
                
                try
                {
                    // Controller_Debug.Controller_TX_TextLoad(tempdata);
                }
                catch { }
            }
            //취소버튼 클릭시 또는 ESC키로 파일창을 종료 했을경우
            else if (dr == DialogResult.Cancel)
            {
            }
        }

        private void button_DownloadStart_Click(object sender, EventArgs e)
        {
            byte[] tempdata = new byte[1027];
            string MBIC_HeaderFileName = "jhfs-mbic-nrdas-v00.00." + this.main.numericUpDown_Version3.Text + ".mbc";
            char[] tempchardata;
            int TotalFrame = 0;
            UInt32 Crcret = 0;
            int i = 0;
            int SendDataLength = 0;
            UInt16 CrcRet = 0;
            string s3 = DateTime.Now.ToString("yyMMddHHmmss");

            if (fileName == null)
                return;
            this.main.Invoke(new TimerSend(Timer_Set), this.main.timer_JdasMbic, false);
            tempchardata = MBIC_HeaderName.ToCharArray();
            for (i = 0; i < tempchardata.Length; i++)
            {
                MBIC_Add_BootLoader_DataArray[i] = Convert.ToByte(tempchardata[i]);
            }
            MBIC_Add_BootLoader_DataArray[9] = 0x20; //file type : MBIC 0x20
            MBIC_Add_BootLoader_DataArray[10] = 0x00; //file type : CPU 0x00
            MBIC_Add_BootLoader_DataArray[11] = 0x00;//version
            MBIC_Add_BootLoader_DataArray[12] = 0x00;//version
            MBIC_Add_BootLoader_DataArray[13] = 0x01;//version

            tempchardata = MBIC_HeaderFileName.ToCharArray();
            for (i = 14; i < 14 + tempchardata.Length + 12; i++) // Total 41byte Filename
            {
                try
                {
                    MBIC_Add_BootLoader_DataArray[i] = Convert.ToByte(tempchardata[i - 14]);
                }
                catch
                {
                    MBIC_Add_BootLoader_DataArray[i] = 0x20;
                }
            }

            tempchardata = s3.ToCharArray();
            for (i = 55; i < 54 + tempchardata.Length / 2 + 1; i++)
            {
                MBIC_Add_BootLoader_DataArray[i] = this.main.DataToConvertHex(s3)[i - 55];
            }

            MBIC_BootLoader_DataArray = File.ReadAllBytes(Mbic_ofd.FileName);
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0xFF00) >> 8);
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0x00FF));

            Crcret = this.main.crc32(MBIC_BootLoader_DataArray, Convert.ToUInt32(MBIC_BootLoader_DataArray.Length));
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte((Crcret & 0xFF000000) >> (8 * 3));
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte((Crcret & 0x00FF0000) >> (8 * 2));
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte((Crcret & 0x0000FF00) >> (8 * 1));
            MBIC_Add_BootLoader_DataArray[i++] = Convert.ToByte((Crcret & 0x000000FF) >> (8 * 0));

            for (i = 0; i < 62; i++)
                MBIC_Add_BootLoader_DataArray[66 + i] = 0x00;

            byte[] RetBinary = new byte[MBIC_Add_BootLoader_DataArray.Length + MBIC_BootLoader_DataArray.Length];
            Array.Copy(MBIC_Add_BootLoader_DataArray, 0, RetBinary, 0, MBIC_Add_BootLoader_DataArray.Length);
            Array.Copy(MBIC_BootLoader_DataArray, 0, RetBinary, MBIC_Add_BootLoader_DataArray.Length, MBIC_BootLoader_DataArray.Length);

            //                System.IO.FileStream infile = new System.IO.FileStream("FileName.bin", System.IO.FileMode.Create); //파일 스트림 선언
            //infile.Write(RetBinary, 0, RetBinary.Length);    //쓰기
            //                infile.Close();                  //꼭 닫아 주세요. 파일 입출력엔 엄청 중요하죠.

            MBIC_BootLoaderData = bluecell_BootProtocol.MBIC_HeaderMergeFunction(RetBinary, RetBinary.Length);

            /*Download Start Request*/
            /*tempdata[0] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0xFF000000) >> 24);
            tempdata[1] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0x00FF0000) >> 16);
            tempdata[2] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0x0000FF00) >> 8);
            tempdata[3] = Convert.ToByte(((MBIC_BootLoader_DataArray.Length + 128) & 0x000000FF));*/
            TotalFrame = MBIC_BootLoader_DataArray.Length / 1024;
            if (MBIC_BootLoader_DataArray.Length % 1024 > 0)
            {
                TotalFrame += 1;
            }

            tempdata[0] = Convert.ToByte(((TotalFrame) & 0xFF000000) >> 24);
            tempdata[1] = Convert.ToByte(((TotalFrame) & 0x00FF0000) >> 16);
            tempdata[2] = Convert.ToByte(((TotalFrame) & 0x0000FF00) >> 8);
            tempdata[3] = Convert.ToByte(((TotalFrame) & 0x000000FF));
            tempdata[4] = 0;
            tempdata[5] = 0;
            tempdata[6] = 0;
            tempdata[7] = 0;
            tempdata = bluecell_BootProtocol.MBIC_HeaderMergeFunction(tempdata, 8);
            tempdata[(int)MBICProt_st.MBIC_CMD_0] = 0x10;

            SendDataLength = 8 + 22 + 3;
            tempdata[(int)MBICProt_st.MBIC_LENGTH_0] = 0x00;
            tempdata[(int)MBICProt_st.MBIC_LENGTH_1] = (Byte)(SendDataLength - 25);
            tempdata[(int)MBICProt_st.MBIC_HEADERCHECKSUM_0] = this.main.crc.Chksum_Create(tempdata);


            CrcRet = this.main.crc.MBIC_CRC16_Generate(tempdata, SendDataLength - 25); //Length = Total Length - Header Length - Taile Length
            tempdata[SendDataLength - 3] = Convert.ToByte((CrcRet & 0xFF00) >> 8);
            tempdata[SendDataLength - 2] = Convert.ToByte(CrcRet & 0x00FF);
            tempdata[SendDataLength - 1] = 0x03;


            this.main.serial.Serial_DataSend(tempdata, 8 + 22 + 3);
            //this.serial.Serial_DataSend(MBIC_BootLoaderData, 1024 + 22 + 3);

            /*    
                tempdata[0] = 0xbe;
                tempdata[1] = Termianl_Reset;
                tempdata[2] = 0x02;
                tempdata[3] = STH30_CreateCrc(tempdata, tempdata[2]);
                tempdata[4] = 0xeb;
                this.serial.Serial_DataSend(tempdata, 5);*/
        }
        public void ProgressbarUpdate(int TotalFrame,int CurrFrame)
        {
            if (CurrFrame > 500)
                return;

            progressBar_mbic.Maximum = TotalFrame;
            progressBar_mbic.Value = (CurrFrame);
            label_Percent.Text = CurrFrame.ToString() + " / " + TotalFrame.ToString();
            TotalFrame *= 1024;
            CurrFrame *= 1024;
            label_Size.Text = CurrFrame.ToString() + " / " + TotalFrame.ToString();
        }
        public void DownloadResult()
        {
            textBox_Result.Text = "Success";
            this.main.Invoke(new TimerSend(Timer_Set), this.main.timer_JdasMbic, true);
            //((JdasMbic)(this.Owner)).timer_JdasMbic.Start(); //타이머를 멈춘다.
        }
        private delegate void TimerSend(object Timer, bool set);
        private void Timer_Set(object Timer, bool set)
        {
            Timer tmp_timer = (Timer)Timer;
            if(set == true)
            {
                tmp_timer.Start();
            }
            else
            {
                tmp_timer.Stop();
            }
        }
    }
}
