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;
using System.Drawing.Drawing2D;
using Newtonsoft.Json.Converters;
using AR;
using Org.BouncyCastle.Pkcs;

namespace UniMarc
{
    public enum SaveTarget
    {
        SpecsMarc,
        MasterMarc
    }

    public partial class fMarc_Editor : Form
    {
        string idx;
        public int row;
        Helper_DB db = new Helper_DB();
        String_Text st = new String_Text();
        Help008Tag tag008 = new Help008Tag();
        MarcEditorControl marcEditorControl1;
        private MacEditorParameter _param;

        SaveTarget Target;

        public fMarc_Editor(string isbn, string marcstring, SaveTarget _target, string etc1, string etc2, int grade)
        {
            InitializeComponent();
            db.DBcon();
            this.etc1.Text = etc1;
            this.etc2.Text = etc2;

            this.uC_SelectGrade1.Grade = grade;
            //if (grade == 0) radA.Checked = true;
            //else if (grade == 1) radB.Checked = true;
            //else if (grade == 2) radC.Checked = true;
            //else if (grade == 3) radD.Checked = true;
            //else radC.Checked = true;

            Target = _target;
            marcEditorControl1 = new MarcEditorControl();
            marcEditorControl1.db = this.db;
            marcEditorControl1.Dock = DockStyle.Fill;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Controls.Add(marcEditorControl1);
            marcEditorControl1.BringToFront();
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape)
                {
                    this.Close();
                }
            };
        }

        public event EventHandler RequestNext;
        public event EventHandler RequestPrev;

        public class BookUpdatedEventArgs : EventArgs
        {
            public string BookName { get; set; }
            public string Marc { get; set; }
            public string ISBN { get; set; }
            public string Author { get; set; }
            public string Publisher { get; set; }
            public string Price { get; set; }
            public string Grade { get; set; }
            public string Etc1 { get; set; }
            public string Etc2 { get; set; }
            public string SaveDate { get; set; }
            public string User { get; set; }
        }

        public event EventHandler RequestFillBlankData;

        public void OpenFillBlank(List<FillBlankItem> gridData, string currentIsbn)
        {
            var fb = new UniMarc.Marc_FillBlank();
            foreach (var item in gridData)
            {
                fb.InitFillBlank(item);
            }
            fb.ISBN = currentIsbn;

            if (fb.ShowDialog() == DialogResult.OK)
            {
                BulkBooksUpdated?.Invoke(this, new BulkBookUpdatedEventArgs { Updates = fb.FillBlankItems });
            }
        }

        public class BulkBookUpdatedEventArgs : EventArgs
        {
            public List<FillBlankItem> Updates { get; set; }
        }

        public event EventHandler<BulkBookUpdatedEventArgs> BulkBooksUpdated;



        public event EventHandler<BookUpdatedEventArgs> BookUpdated;


        private string mk_BookName(string[] book_name)
        {
            string a245 = book_name[0];     // 도서명
            string x245 = book_name[1];     // 대동서명
            string b245 = book_name[2];     // 부서명

            string result = a245;

            if (x245 != "")
                result += " = " + x245;

            if (b245 != "")
                result += " : " + b245;

            return result;
        }

        public void LoadBook(string dbMarc, MacEditorParameter p)
        {
            this._param = p;
            this._param.OriginalMarc = dbMarc; // 원본 마크 저장 (MasterMarc 저장 시 필요)
            this.Text = $"마크편집({p.ISBN13})-{p.BookName} Database:{Target}";
            marcEditorControl1.LoadBookData(dbMarc, p.ISBN13);
        }

        private void Marc_Plan_Sub_MarcEdit2_Load(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
        }

        private void btn_FillBlank_Click(object sender, EventArgs e)
        {
            RequestFillBlankData?.Invoke(this, EventArgs.Empty);
        }

        private void btPrev_Click(object sender, EventArgs e)
        {
            RequestPrev?.Invoke(this, EventArgs.Empty);
        }

        private void btNext_Click(object sender, EventArgs e)
        {
            RequestNext?.Invoke(this, EventArgs.Empty);
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (marcEditorControl1.CheckValidation() == false) return;

            string oriMarc = marcEditorControl1.MakeMarcString();
            string etc1Value = etc1.Text.Trim();
            string etc2Value = etc2.Text.Trim();
            string tag008Value = marcEditorControl1.text008.Text;

            var v_grade = uC_SelectGrade1.Grade < 0 ?  "2" : uC_SelectGrade1.Grade.ToString() ;

            // Extract tags for metadata
            string[] Search_Tag = {
                "049l", "090a", "090b", "049v", "049c",
                "049f", "440a", "440v", "245d", "260b",
                "950b", "020a"
            };
            string[] SearchBookTag = st.Take_Tag(oriMarc, Search_Tag);

            // 도서명 (본서명 = 대등서명 : 부서명)
            string[] BookTag = { "245a", "245x", "245b" };
            string[] BookNameTag = st.Take_Tag(oriMarc, BookTag);
            string BookName = mk_BookName(BookNameTag);

            var updateData = new Dictionary<string, object>();
            var whereClause = new Dictionary<string, object>();
            string Table = "";

            var idx = (Target == SaveTarget.SpecsMarc ? _param.ListIdx : _param.MarcIdx);
            if (Target == SaveTarget.SpecsMarc)
            {
                Table = "Specs_Marc";
                whereClause.Add("idx", idx);

                updateData.Add("marc", oriMarc);
                updateData.Add("book_name", BookName);
                updateData.Add("etc1", etc1Value);
                updateData.Add("etc2", etc2Value);
                updateData.Add("r_num", SearchBookTag[0]);
                updateData.Add("class_symbol", SearchBookTag[1]);
                updateData.Add("author_symbol", SearchBookTag[2]);
                updateData.Add("prefix", SearchBookTag[5]);
                updateData.Add("s_book_name1", SearchBookTag[6]);
                updateData.Add("s_book_num1", SearchBookTag[7]);
                updateData.Add("author", SearchBookTag[8]);
                updateData.Add("book_comp", SearchBookTag[9]);
                updateData.Add("price", SearchBookTag[10]);
                updateData.Add("ISBN", SearchBookTag[11]);
                updateData.Add("tag008", tag008Value);
                
                if (!v_grade.isEmpty())
                    updateData.Add("grade", v_grade);
            }
            else // MasterMarc
            {
                Table = "Marc";
                whereClause.Add("idx", idx);
                whereClause.Add("compidx", PUB.user.CompanyIdx);

                string today = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                updateData.Add("marc", oriMarc);
                updateData.Add("marc_chk", "1");
                updateData.Add("marc1", _param.OriginalMarc);
                updateData.Add("marc_chk2", "0");
                updateData.Add("date", today);
                updateData.Add("user", PUB.user.UserName);
                updateData.Add("비고1", etc1Value);
                updateData.Add("비고2", etc2Value);

                if (!v_grade.isEmpty())
                    updateData.Add("grade", v_grade);
            }

            string cmd = Helper_DB.Make_UpdateQuery(Table, updateData, whereClause);
            var rlt = Helper_DB.ExcuteNonQuery(cmd);
            if (rlt.applyCount == 1)
            {
                // Notify Parent
                BookUpdated?.Invoke(this, new BookUpdatedEventArgs
                {
                    BookName = BookName,
                    Marc = oriMarc,
                    ISBN = SearchBookTag[11],
                    Author = SearchBookTag[8],
                    Publisher = SearchBookTag[9],
                    Price = SearchBookTag[10],
                    Grade = v_grade,
                    Etc1 = etc1Value,
                    Etc2 = etc2Value,
                    SaveDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    User = PUB.user.UserName
                });

                UTIL.MsgI($"저장되었습니다!\nDatabase = {this.Target}");
            }
            else if (rlt.applyCount == 0)
            {
                UTIL.MsgE($"저장된 자료가 없습니다\nTable:{Table}, IDX:{idx}\n\n개발자 문의 하세요");
            }
            else if (rlt.applyCount > 1)
            {
                UTIL.MsgE($"복수개({rlt.applyCount})의 자료가 업데이트 되었습니다\nTable:{Table}, IDX:{idx}\n\n개발자 문의 하세요");
            }
        }

        private void btn_close_Click(object sender, EventArgs e)
        {

        }

        private void etc1_KeyDown(object sender, KeyEventArgs e)
        {
            var rt = sender as RichTextBox;
            if (rt == null) return;
            if (e.KeyCode == Keys.F5)
            {
                rt.AppendText("[" + DateTime.Now.ToString("yy-MM-dd") + "]");
            }
        }
    }
}
