using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            /*
                               // 리더부
            string Marc_data = "00494nam  2200193 k 4500" +
                               // 디렉토리
                               "005001500000" +
                               "008004100015" +
                               "020003300056" +
                               "049001700089" +
                               "056001300106" +
                               "090001800119" +
                               "100001100137" +
                               "245004100148" +
                               "260002100189" +
                               "300001600210" +
                               "500001300226" +
                               "653003900239" +
                               "700001100278" +
                               "950001100289▲" +
                               // 가변길이필드
                               "20200213170911▲" +
                               "200213s2019    ggk    c      000 f kor  ▲" +
                               "  ▼a9788936459093▼g43810▼c\\12000▲" +
                               "0 ▼lJM0000045930▲" +
                               "  ▼a813.7▼25▲" +
                               "  ▼a813.7▼b이98페▲" +
                               "1 ▼a이희영▲" +
                               "00▼a페인트▼b이희영 장편소설▼d이희영 지음▲" +
                               "  ▼a파주▼b창비▼c2019▲" +
                               "  ▼a228p.▼c28cm▲" +
                               "  ▼a양장본임▲" +
                               "  ▼a페인트▼a창비청소년문학▼a청소년소설▲" +
                               "1 ▼a이희영▲" +
                               "0 ▼b\\12000▲↔";
            */
            string Marc_data = "00622nam  2200205 k 4500" +

                               "005001500000" +
                               "008004100015" +
                               "020003300056" +
                               "020002400089" +
                               "049002100113" +
                               "056001300134" +
                               "090001800147" +
                               "245007200165" +
                               "260003900237" +
                               "300002800276" +
                               "653005300304" +
                               "700001100357" +
                               "740001400368" +
                               "940002300382" +
                               "950001100405▲" +
                               
                               "20210219095445▲" +
                               "210219s2021    ulka   j      000   kor  ▲" +
                               "  ▼a9788931461213▼g94000▼c\\15000▲" +
                               "1 ▼a9788931461220(세트)▲" +
                               "0 ▼lEM0000166080▼f아▲" +
                               "  ▼a005.1▼25▲" +
                               "  ▼a005.1▼b안79ㅈ▲" +
                               "20▼a(알버트 AI로봇과 함께하는) 즐거운 엔트리 코딩▼b스택 코딩▼d안진석 저▲" +
                               "  ▼a서울▼bYoungjin.com(영진닷컴)▼c2021▲" +
                               "  ▼a156p.▼b천연색삽화▼c29cm▲" +
                               "  ▼aAI로봇▼a엔트리▼a코딩▼a스택코딩▼a초등컴퓨터▼a아동▲" +
                               "1 ▼a안진석▲" +
                               "02▼a스택 코딩▲" +
                               "0 ▼a즐거운 엔트리 코딩▲" +
                               "0 ▼b\\15000▲↔";

            // 마크 원본을 편집기 스타일로 가공

            Marc_data = Marc_data.Replace("", "▼");
            Marc_data = Marc_data.Replace("", "▲");
            string leader = Marc_data.Substring(0, 24);
            int startidx = 0;
            label1.Text = leader;
            string[] data = Marc_data.Substring(24).Split('▲');
            string[] input = { "", "" };
            for (int a = 1; a < data.Length-1; a++) 
            {
                input[0] = data[0].Substring(startidx, 12); 
                startidx += 12; 

                input[1] = data[a] + "▲";
                dataGridView1.Rows.Add(input);
            }
            for (int a= 0; a < dataGridView1.Rows.Count; a++)
            {
                string result1 = dataGridView1.Rows[a].Cells[0].Value.ToString().Substring(0,3);
                if (dataGridView1.Rows[a].Cells[1].Value.ToString().IndexOf("▼") == -1) {
                    result1 += "\t  \t" + dataGridView1.Rows[a].Cells[1].Value.ToString();
                }
                else {
                    string temp = dataGridView1.Rows[a].Cells[1].Value.ToString().Insert(2, "\t");
                    result1 += "\t" + temp;
                }
                richTextBox1.Text += result1 + "\n";
            }

            // 편집기 스타일 마크를 원본으로 가공
            
            string text = richTextBox1.Text.Replace("\t", "");
            string[] array_text = text.Split('\n');

            /// num+count+total = 디렉토리
            List<string> num = new List<string>();
            List<string> count = new List<string>();
            List<string> total = new List<string>();

            for(int a = 0; a < array_text.Length - 1; a++)
            {
                num.Add(array_text[a].Substring(0,3));      // 태그넘버 저장
                if (array_text[a][5]== '▼') {
                    array_text[a] = array_text[a].Remove(0, 3);
                }
                else { array_text[a] = array_text[a].Remove(0, 5); }
                richTextBox2.Text += array_text[a] + "\n";
                int textLength = Encoding.Default.GetBytes(array_text[a]).Length
                    - WordCheck(array_text[a], "▲")
                    - WordCheck(array_text[a], "▼");

                count.Add(insert_Zero(textLength, 4));
            }

            for(int a= 0; a < array_text.Length; a++)
            {
                if (a == 0) { total.Add("0"); }
                else if (a > 1)
                {
                    int b = Convert.ToInt32(total[total.Count - 1]);
                    int c = Convert.ToInt32(Encoding.Default.GetBytes(array_text[a - 2]).Length.ToString())
                        - WordCheck(array_text[a - 2], "▲")
                        - WordCheck(array_text[a - 2], "▼");
                    int res = b + c;
                    total.Add(res.ToString());
                }
            }

            string[] str_num = num.ToArray();
            for(int a= 0; a < str_num.Length; a++)
            {
                if (total[a].Length == 4) { total[a] = total[a].Insert(0, "0"); }
                else if (total[a].Length == 3) { total[a] = total[a].Insert(0, "00"); }
                else if (total[a].Length == 2) { total[a] = total[a].Insert(0, "000"); }
                else if (total[a].Length == 1) { total[a] = total[a].Insert(0, "0000"); }
                richTextBox3.Text += str_num[a] + count[a] + total[a] + "\n";
            }

            // 00494nam  2200193 k 4500
            string[] reader = { "00000", "n", "a", "m", " ",
                                " ", "2", "2", "00000", " ",
                                "k", " ", "4", "5", "0",
                                "0" };
            richTextBox2.Text += "↔";
            richTextBox3.Text += "▲";
            string 디렉토리 = richTextBox3.Text.Replace("\n", "");
            string 가변길이 = richTextBox2.Text.Replace("\n", "");
            string dp = 가변길이 + 디렉토리;
            int recode = Encoding.Default.GetBytes(dp).Length
                        - WordCheck(dp, "▲") - WordCheck(dp, "▼") - WordCheck(dp, "↔");
            reader[0] = insert_Zero(recode + 24, 5);

            int data_addr = 24 + Encoding.Default.GetBytes(디렉토리).Length - WordCheck(디렉토리, "▲");
            reader[8] = insert_Zero(data_addr, 5);

            for(int a = 0; a < reader.Length; a++)
            {
                textBox1.Text += reader[a];
            }

            string result = textBox1.Text + 디렉토리 + 가변길이;
            if (Marc_data == result)
            {
                label3.Text = "True";
            }
            else { label3.Text = "False"; }
            label4.Text = Encoding.Default.GetBytes(Marc_data).Length.ToString();
        }
        int WordCheck(string String, string Word)
        {
            string[] StringArray = String.Split(new string[] { Word }, StringSplitOptions.None);
            return StringArray.Length - 1;
        }
        string insert_Zero(int value, int count)
        {
            string result = string.Empty;
            switch (count)
            {
                case 5:
                    if (value < 10) { result = "0000"; }
                    else if (value < 100) { result = "000"; }
                    else if (value < 1000) { result = "00"; }
                    else if (value < 10000) { result = "0"; }
                    break;
                case 4:
                    if (value < 10) { result = "000"; }
                    else if (value < 100) { result = "00"; }
                    else if (value < 1000) { result = "0"; }
                    break;
                default:
                    break;
            }
            result += value.ToString();
            return result;
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1) {
                int idx = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().IndexOf("▼");
                label2.Text = idx.ToString();
            }
        }
    }
}