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;

namespace UniMarc
{
    public partial class Marc_Plan_Sub_MarcEdit2 : Form
    {
        string idx;
        public int row;
        public string UserName = "";
        Marc_Plan mp;
        Helper_DB db = new Helper_DB();
        String_Text st = new String_Text();
        Search_Infor si;
        Help008Tag tag008 = new Help008Tag();
        MarcEditorControl marcEditorControl1;
        public Marc_Plan_Sub_MarcEdit2(string isbn,string marcstring)
        {
            InitializeComponent();
            db.DBcon();
            marcEditorControl1 = new MarcEditorControl();
            marcEditorControl1.db = this.db;
            marcEditorControl1.FillBlankClicked += MarcEditorControl_FillBlankClicked;
            marcEditorControl1.BookSaved += MarcEditorControl_BookSaved;
            marcEditorControl1.NextButton += MarcEditorControl1_NextButton;
            marcEditorControl1.PrevButton += MarcEditorControl1_PrevButton;
            marcEditorControl1.CloseButton += (s1, e1) => { this.Close(); };
            marcEditorControl1.Dock = DockStyle.Fill;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Controls.Add(marcEditorControl1);
            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 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)
            {
                // Handle results
                // We don't have direct access to 'BulkMarcResults' here easily unless we iterate.
                // But wait, BookUpdated event is for single update.
                // Marc_Plan expects 'RequestFillBlankData' to handle the *opening*, but it doesn't handle the *return* logic for bulk updates within Marc_Plan.
                // The current architecture: Marc_Plan_Sub_MarcEdit2 raises RequestFillBlankData -> Marc_Plan calls OpenFillBlank.
                // So now OpenFillBlank is running. When it returns, we have data.
                // We need to pass this data BACK to Marc_Plan.
                // I will add a 'BulkBooksUpdated' event or reuse 'BookUpdated' (but BookUpdated is single).
                // Let's create 'BulkBooksUpdated'.
                
                BulkBooksUpdated?.Invoke(this, new BulkBookUpdatedEventArgs { Updates = fb.BulkMarcResults });
            }
        }
        
        public class BulkBookUpdatedEventArgs : EventArgs
        {
            public Dictionary<int, string> Updates { get; set; }
        }
        
        public event EventHandler<BulkBookUpdatedEventArgs> BulkBooksUpdated;

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



        public event EventHandler<BookUpdatedEventArgs> BookUpdated;

        private void MarcEditorControl_BookSaved(object sender, MarcEditorControl.BookSavedEventArgs e)
        {
            // Update Specs_Marc table
            string oriMarc = e.DBMarc;
            string etc1 = e.Param.Remark1 ?? "";
            string etc2 = e.Param.Remark2 ?? "";
            string tag008 = e.Param.text008;

            // 등록번호 분류기호 저자기호 볼륨 복본
            // 별치     총서명  총서번호  저자 출판사
            // 정가    ISBN
            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);

            string Table = "Specs_Marc";
            string[] Search_Col = { "idx" };

            // Current ListIdx (Wait, idx in Marc_Plan corresponds to ListIdx in Parameter?)
            // In Marc_Plan: ListIdx = idx.
            string listIdx = e.Param.ListIdx;
            string[] Search_data = { listIdx };

             string[] Update_Col = {
                "marc", "book_name", "etc1", "etc2",
                "r_num", "class_symbol", "author_symbol", "prefix", "s_book_name1",
                "s_book_num1", "author", "book_comp", "price", "ISBN", "tag008"
            };
            string[] Update_data = {
                oriMarc, BookName, etc1, etc2,
                SearchBookTag[0], SearchBookTag[1], SearchBookTag[2], SearchBookTag[5], SearchBookTag[6],
                SearchBookTag[7], SearchBookTag[8], SearchBookTag[9], SearchBookTag[10], SearchBookTag[11], tag008
            };

            string cmd = db.More_Update(Table, Update_Col, Update_data, Search_Col, Search_data);
            Helper_DB.ExcuteNonQuery(cmd);

            // Notify Parent
            BookUpdated?.Invoke(this, new BookUpdatedEventArgs { BookName = BookName, Marc = oriMarc });
            
            MessageBox.Show("저장되었습니다!");
        }

        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;
        }

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

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

        public void LoadBook(string dbMarc, MacEditorParameter p)
        {
            this.Text = $"마크편집({p.ISBN13})-{p.BookName}";
            marcEditorControl1.LoadBookData(dbMarc, p);
        }

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