using AR;
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.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class Mac_Input : Form
    {
        Helper_DB db = new Helper_DB();
        Main main;
        public Mac_Input(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Mac_Input_Load(object sender, EventArgs e)
        {
            db.DBcon();

            string[] com_list = { "표준Marc", "라인Marc" };
            comboBox1.Items.AddRange(com_list);
            comboBox1.SelectedIndex = 0;
        }
        private void btn_FileOpen_Click(object sender, EventArgs e)
        {
            string file_path = string.Empty;
            if (tb_filePath.Text != "")
            {
                openFileDialog1.InitialDirectory = tb_filePath.Text;
            }
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                file_path = openFileDialog1.FileName;
                dataGridView1.Rows.Clear();
                try
                {
                    StreamReader r = new StreamReader(file_path, Encoding.Default);
                    input_Grid(r.ReadToEnd());

                    r.Close();
                }
                catch(Exception ex)
                {
                    // 
                    UTIL.MsgE(ex.ToString());
                }
            }
            tb_filePath.Text = file_path;
        }
        void input_Grid(string text)
        {
            String_Text st = new String_Text();
            string[] grid = text.Split('');
            for (int a = 0; a < grid.Length - 1; a++)
            {
                if (comboBox1.SelectedIndex != 0)
                    grid[a] = grid[a].Replace("\r\n", "");

                // string[] data = Split_Marc(grid[a]);
                // data[0] = data[0].Replace(":", "");
                // data[6] = grid[a] + "";

                string[] Tag = { "020a", "245a", "440a", "245d", "260b", "950b", "008", "950a" };
                string[] data = st.Take_Tag(grid[a], Tag);
                data[7] = grid[a] + "";
                dataGridView1.Rows.Add(data);
            }
        }
        string[] Split_Marc(string text)
        {
            string tmp_string = text.Remove(0, 24);
            string[] Marc = tmp_string.Split('');
            string[] dir = made_Directory(Marc[0]);
            string[] data = { "", "", "", "", "", "", "" };     // isbn, 도서명, 총서명, 저자, 출판사, 정가, marc
            String_Text st = new String_Text();

            for(int a = 0; a < dir.Length; a++)
            {
                if (dir[a] == "020")
                {
                    data[0] = st.GetMiddelString(Marc[a + 1], "a", "");    // isbn
                    data[5] = st.GetMiddelString(Marc[a + 1], "c", "");    // 정가
                }
                if (dir[a] == "245")
                {
                    data[1] = st.GetMiddelString(Marc[a + 1], "a", "");    // 도서명
                    data[3] = st.GetMiddelString(Marc[a + 1], "d", "");    // 저자
                }
                if (dir[a] == "260")
                {
                    data[4] = st.GetMiddelString(Marc[a + 1], "b", "");    // 출판사
                }
                if (dir[a] == "440")
                {
                    data[2] = st.GetMiddelString(Marc[a + 1], "a", "");    // 총서명
                }
                if (dir[a] == "950")
                {
                    data[5] = st.GetMiddelString(Marc[a + 1], "b", "");    // 정가
                }
            }
            return data;
        }
        string[] made_Directory(string value)
        {
            int length = value.Length;
            int start = 0;
            List<string> L_dir = new List<string>();
            while (true)
            {
                if (start + 12 > length) { break; }
                L_dir.Add(value.Substring(start, 3));
                start += 12;
            }
            string[] result = L_dir.ToArray();
            
            return result;
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }
        private void btn_db_save_Click(object sender, EventArgs e)
        {
            string Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string user = PUB.user.UserName;
            string compidx = PUB.user.CompanyIdx;// UniMarc.Properties.Settings.Default.compidx;
            string table = "Marc";
            string[] GridCol = { "isbn", "book_name", "series", "author", "book_comp", "price" };

            string[] col = {
                "ISBN", "서명", "총서명", "저자", "출판사", "가격",
                "marc", "marc_chk", "compidx", "grade", "date",
                "user", "008tag" };
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                foreach (string colName in GridCol)
                {
                    if (dataGridView1.Rows[a].Cells[colName].Value == null)
                        dataGridView1.Rows[a].Cells[colName].Value = "";
                }
                string Marc = dataGridView1.Rows[a].Cells["Marc"].Value.ToString();
                string tag008 = dataGridView1.Rows[a].Cells["tag008"].Value.ToString();
                Marc = Marc.Replace(@"'", "'");
                Marc = Marc.Replace(@"""", "\"\"");
                try
                {
                    string[] data = { dataGridView1.Rows[a].Cells["isbn"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["book_name"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["series"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["author"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["book_comp"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["price"].Value.ToString(),
                                      Marc, "1", compidx, "2", Time,
                                      user, tag008 };

                    // string Incmd = db.DB_INSERT_DUPLICATE(table, col, data);
                    string Incmd = db.DB_INSERT(table, col, data);
                    Helper_DB.ExcuteNonQuery(Incmd);
                }
                catch (Exception ex) { UTIL.MsgE(ex.Message); }
            }
            UTIL.MsgI("DB 저장 완료!");
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.clipboard_not_crack(sender, e);
        }
    }
}
