using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.Delivery;
using WindowsFormsApp1.마크;
namespace WindowsFormsApp1.Mac
{
    public partial class Check_ISBN : Form
    {
        Main main;
        List_aggregation list_agg;
        Commodity_registration cr;
        Helper_DB db = new Helper_DB();
        public string compidx;
        public string list_name = string.Empty;
        private int rowidx;
        private bool save = true;
        public Check_ISBN(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
        }
        public Check_ISBN(List_aggregation _list_agg)
        {
            InitializeComponent();
            list_agg = _list_agg;
            compidx = list_agg.compidx;
        }
        public Check_ISBN(Commodity_registration _cr)
        {
            InitializeComponent();
            cr = _cr;
            compidx = cr.comp_idx;
        }
        private void Check_ISBN_Load(object sender, EventArgs e)
        {
            tb_list_name.Text = compidx + " " + list_name;
            string[] list_combo = { "알라딘", "네이버", "다음" };
            cb_api.Items.AddRange(list_combo);
            db.DBcon();
            string[] search_tbl = { "compidx", "list_name" };
            string[] search_col = { compidx, list_name };
            string search_data = "`header`, `num`, `isbn`, `book_name`, `author`, `book_comp`, " +
                                 "`count`, `pay`, `total`, `import`, `price`, " +
                                 "`etc`, `pubDate`, `persent`, `category`, `image_url`";
            string tmp_data = db.More_DB_Search("Obj_List_Book", search_tbl, search_col, search_data);
            string[] data = tmp_data.Split('|');
            made_Grid(data);
        }
        private void btn_lookup_Click(object sender, EventArgs e)
        {
            if (cb_api.SelectedIndex == -1) { MessageBox.Show("조건이 선택되지 않았습니다."); return; }
            if (cb_filter.SelectedIndex == -1) { MessageBox.Show("조건이 선택되지 않았습니다."); return; }
            clear_api();
            progressBar1.Style = ProgressBarStyle.Continuous;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = dataGridView1.Rows.Count;
            progressBar1.Step = 1;
            progressBar1.Value = 0;
            switch (cb_api.SelectedIndex)
            {
                case 0:
                    Aladin_API(dataGridView1);
                    break;
                case 1:
                    Naver_API(dataGridView1);
                    break;
                case 2:
                    Daum_API(dataGridView1);
                    break;
            }
            // 총 검색 횟수, 일치, 중복
            MessageBox.Show("검색이 완료되었습니다!");
            progressBar1.Value = dataGridView1.Rows.Count;
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
            this.ActiveControl = dataGridView1;
            rowidx = 0;
            save = false;
        }
        /// 
        /// 불러와서 저장한 api값 초기화
        /// 
        void clear_api()
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["api_data"].Value = "";
            }
        }
        private void Aladin_API(DataGridView gridview)
        {
            string temp = string.Empty;
            string type = string.Empty;
            string query = string.Empty;
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn13", "priceStandard", 
                               "pubDate", "categoryName", "stockStatus", "cover" };
            API api = new API();
            switch (cb_filter.SelectedIndex)
            {
                case 0:
                    type = "Keyword";
                    break;
                case 1:
                    type = "Title";
                    break;
                case 2:
                    type = "Author";
                    break;
                case 3:
                    type = "Publisher";
                    break;
            }
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++) 
            {
                progressBar1.PerformStep();
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow) 
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                query = Aladin_Set_query(type, a);
                insert_Aladin(api.Aladin(query, type, param), a);
            }
        }
        string Aladin_Set_query(string type, int idx)
        {
            string result = string.Empty;
            if (type == "Keyword")
                result = dataGridView1.Rows[idx].Cells["book_name"].Value.ToString() +
                         dataGridView1.Rows[idx].Cells["author"].Value.ToString();
            if (type == "Title")
                result = dataGridView1.Rows[idx].Cells["book_name"].Value.ToString();
            if (type == "Author")
                result = dataGridView1.Rows[idx].Cells["author"].Value.ToString();
            if (type == "Publisher")
                result = dataGridView1.Rows[idx].Cells["book_comp"].Value.ToString();
            return result;
        }
        private void Naver_API(DataGridView gridview)
        {
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn", "price", 
                               "pubdate", "discount", "image"};
            API api = new API();
            List L_type = new List();
            List L_Array = new List();
            
            for(int a = 0; a < gridview.Rows.Count; a++)
            {
                L_type.Clear();
                L_Array.Clear();
                progressBar1.PerformStep();
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow)
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                #region 필터적용
                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        L_type.Add("d_titl");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        break;
                    case 1:
                        L_type.Add("d_auth");
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        break;
                    case 2:
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;
                    case 3:
                        L_type.Add("d_titl");
                        L_type.Add("d_auth");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        break;
                    case 4:
                        L_type.Add("d_titl");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;
                    case 5:
                        L_type.Add("d_auth");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;
                    case 6:
                        L_type.Add("d_titl");
                        L_type.Add("d_auth");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;
                }
                #endregion
                string[] arrayType = L_type.ToArray();
                string[] arrayValue = L_Array.ToArray();
                string result = api.Naver(arrayValue, arrayType, param);
                insert_Naver(result, a); 
                Thread.Sleep(700);
            }
        }
        private void Daum_API(DataGridView gridview)
        {
            string[] param = { "title", "authors", "publisher", "isbn", "price", 
                               "datetime", "status", "thumbnail" };
            string type = string.Empty;
            string query = string.Empty;
            API api = new API();
            for(int a = 0; a < gridview.Rows.Count; a++)
            {
                progressBar1.PerformStep();
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow)
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        query = gridview.Rows[a].Cells["book_name"].Value.ToString();
                        break;
                    case 1:
                        type = "person";
                        query = gridview.Rows[a].Cells["author"].Value.ToString();
                        break;
                    case 2:
                        type = "publisher";
                        query = gridview.Rows[a].Cells["book_comp"].Value.ToString();
                        break;
                }
                string result = api.Daum(query, type, param);
                insert_Daum(result, a);
            }
        }
        void insert_Aladin(string data, int row)
        {
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;
            if (data.Length > 0) {
                dataGridView1.Rows[row].Cells["api_data"].Value = data;
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            string[] insert = data.Split('|');
            if (data == "") { return; }
            // pubDate형 보기편하게 DateTime형으로 재정리
            string newstring = String.Format("{0:yyyy/MM/dd HH:mm}", 
                DateTime.Parse(insert[5].Remove(insert[5].IndexOf(" G"))));
            // 도서 분류 필요한 데이터로 재정리
            int top = insert[6].IndexOf('>');
            int mid = insert[6].IndexOf('>', top + 1);
            int bot = insert[6].IndexOf('>', mid + 1);
            if (bot < 0) { insert[6] = insert[6].Substring(top + 1); }
            else { insert[6] = insert[6].Substring(top + 1, bot - top - 1); }
            if (insert.Length > 10) {
                return;
            }
            input_api(insert, row, newstring);
        }
        void insert_Naver(string value, int row)
        {
            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;
            dataGridView1.Rows[row].Selected = true;
            if (value == "") return;
            value = value.Replace("", "");
            value = value.Replace("", "");
            string[] sp_data = value.Split('\t');
            string[] grid = { "", "", "", "", "", "", "", "", "" };
            #region 분류작업
            for (int a = 0; a < sp_data.Length - 1; a++)
            {
                string[] data = sp_data[a].Split('|');
                int idx = data.Length - 2;
                grid[0] = data[0];
                grid[1] = data[1];
                for (int b = 2; b < idx - 5; b++)
                {
                    grid[1] += ", " + data[b];
                }
                grid[2] = data[idx - 5];
                if (data[idx - 4].Contains(" ") == true)
                {
                    string[] isbn = data[idx - 4].Split(' ');
                    grid[3] = isbn[1];
                }
                else
                    grid[3] = data[idx - 4];
                grid[4] = data[idx - 3];
                grid[5] = data[idx - 2];
                if (data[idx - 1] == "")
                    grid[7] = "절판";
                else
                    grid[7] = "";
                grid[8] = data[idx];
                dataGridView1.Rows[row].Cells["api_data"].Value += string.Join("|", grid) + "|";
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            #endregion
            if (sp_data.Length > 10) return;
            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;
            dataGridView1.Rows[row].Selected = true;
            string newstring = "";
            try
            {
                newstring = DateTime.ParseExact(grid[5], "yyyyMMdd", null).ToString("yyyy-MM-dd");
            }
            catch (Exception e)
            {
                MessageBox.Show("[" + grid[5] + "]" + e.ToString());
            }
            input_api(grid, row, newstring);
        }
        void insert_Daum(string value, int row)
        {
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;
            if (value == "") return;
            string[] sp_data = value.Split('\n');
            string[] grid = { "", "", "", "", "", "", "", "", "" };
            for (int a = 0; a < sp_data.Length - 1; a++)
            {
                string[] data = sp_data[a].Split('|');
                grid[0] = data[0];
                grid[1] = data[1];
                grid[2] = data[2];
                string[] tmp_isbn = data[3].Split(' ');
                if (tmp_isbn.Length < 2)
                    grid[3] = data[3].Replace(" ", "");
                else
                    grid[3] = tmp_isbn[1];
                grid[4] = data[4];
                grid[5] = data[5].Substring(0, 10);
                grid[7] = data[6];
                grid[8] = data[7];
                dataGridView1.Rows[row].Cells["api_data"].Value += string.Join("|", grid) + "|";
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            if (sp_data.Length > 10) return;
            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;
            dataGridView1.Rows[row].Selected = true;
            string newstring = grid[5];
            input_api(grid, row, newstring);
        }
        /// 
        /// API에서 가져온 데이터가 요구한 데이터와 일치하는지 알아보는 함수
        /// 
        /// 데이터
        /// Grid의 row인덱스 번호
        /// 날짜
        void input_api(string[] value, int idx, string date)
        {
            bool[] chk = { false, false, false };
            string book_name = dataGridView1.Rows[idx].Cells["book_name"].Value.ToString();
            string author = dataGridView1.Rows[idx].Cells["author"].Value.ToString();
            string book_comp = dataGridView1.Rows[idx].Cells["book_comp"].Value.ToString();
            if (value[0] == book_name) chk[0] = true;
            if (value[1].Contains(author) == true) chk[1] = true;
            else if (author.Contains(value[1]) == true) chk[1] = true;
            else if (value[1] == author) chk[1] = true;
            if (value[2].Contains(book_comp) == true) chk[2] = true;
            else if (book_comp.Contains(value[2]) == true) chk[2] = true;
            else if (value[2] == book_comp) chk[2] = true;
            if (chk[0] == true && chk[1] == true && chk[2] == true) {
                dataGridView1.Rows[idx].Cells["search_book_name"].Value = value[0];
                dataGridView1.Rows[idx].Cells["search_author"].Value = value[1];
                dataGridView1.Rows[idx].Cells["search_book_comp"].Value = value[2];
                dataGridView1.Rows[idx].Cells["isbn"].Value = value[3];
                dataGridView1.Rows[idx].Cells["price"].Value = value[4];
                dataGridView1.Rows[idx].Cells["pubDate"].Value = date;
                dataGridView1.Rows[idx].Cells["category"].Value = value[6];
                dataGridView1.Rows[idx].Cells["sold_out"].Value = value[7];
                dataGridView1.Rows[idx].Cells["image"].Value = value[8];
                dataGridView1.Rows[idx].DefaultCellStyle.BackColor = Color.Yellow;
            }
        }
        void made_Grid(string[] data)
        {
                          /* 번호 isbn 도서명 저자 출판사
                           * 수량 단가 합계 상태 정가
                           * 비고 발행일 % 도서분류 */
            string[] grid = { "", "", "", "", "", 
                              "", "", "", "", "", 
                              "", "", "", "", "", 
                              "", "", "", "" };
            int sdc = 16; // search_data_count
            for (int a = 0; a < data.Length; a++)
            {
                if (a % sdc == 1) { grid[0] = data[a-1] + " " + data[a]; }  // 번호
                if (a % sdc == 2) { grid[1] = data[a]; }                    // isbn
                if (a % sdc == 3) { grid[2] = data[a]; }                    // 도서명
                if (a % sdc == 4) { grid[4] = data[a]; }                    // 저자
                if (a % sdc == 5) { grid[6] = data[a]; }                    // 출판사
                if (a % sdc == 6) { grid[8] = data[a]; }                    // 수량
                if (a % sdc == 7) { grid[9] = data[a]; }                    // 단가
                if (a % sdc == 8) { grid[10] = data[a]; }                    // 합계
                if (a % sdc == 9) { grid[11] = data[a]; }                    // 상태
                if (a % sdc == 10) { grid[12] = data[a]; }                   // 정가
                if (a % sdc == 11) { grid[13] = data[a]; }                  // 비고
                if (a % sdc == 12) { grid[14] = data[a]; }                  // 발행일
                if (a % sdc == 13) { grid[15] = data[a]; }                  // %
                if (a % sdc == 14) { grid[16] = data[a]; }                  // 도서분류
                if (a % sdc == 15) { grid[18] = data[a];                    // 도서 URL
                    dataGridView1.Rows.Add(grid); }
            }
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["isbn"].Value.ToString() != "")
                {
                    if (dataGridView1.Rows[a].Cells["unit"].Value.ToString() != 
                        dataGridView1.Rows[a].Cells["price"].Value.ToString()) {
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Orange;
                    }
                    else {
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                    }
                }
            }
            Set_grid();
        }
        void Set_grid()
        {
            for(int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if(dataGridView1.Columns[a].HeaderText != "ISBN13")
                    dataGridView1.Columns[a].ReadOnly = true;
                
            }
        }
        private void btn_Save_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["isbn"].Value.ToString() == "" ||
                    dataGridView1.Rows[a].Cells["price"].Value.ToString() == "" ||
                    dataGridView1.Rows[a].Cells["pubDate"].Value.ToString() == "") { continue; }
                string[] Edit_tbl = { "isbn", "price", "pubDate", "category", "image_url" };
                string[] Edit_Col = { dataGridView1.Rows[a].Cells["isbn"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["price"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["pubDate"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["category"].Value.ToString(),
                                      dataGridView1.Rows[a].Cells["image"].Value.ToString() };
                string[] Search_tbl = { "book_name", "author", "book_comp", "list_name" };
                string[] Search_col = {dataGridView1.Rows[a].Cells["book_name"].Value.ToString(),
                                       dataGridView1.Rows[a].Cells["author"].Value.ToString(),
                                       dataGridView1.Rows[a].Cells["book_comp"].Value.ToString(),
                                       list_name };
                db.More_Update("Obj_List_Book", Edit_tbl, Edit_Col, Search_tbl, Search_col);
            }
            MessageBox.Show("저장되었습니다!");
            save = true;
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (rowidx >= dataGridView1.Rows.Count) return;
            if (dataGridView1.Rows[rowidx].Cells["api_data"].Value == null || 
                dataGridView1.Rows[rowidx].Cells["api_data"].Value.ToString() == "") { 
                return; 
            }
            Check_ISBN_Sub sub = new Check_ISBN_Sub(this);
            sub.row = rowidx;
            sub.Call_API = cb_api.Text;
            sub.Show();
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { dataGridView1_CellDoubleClick(null, null); rowidx++; }
            if (e.KeyCode == Keys.Up)
            {
                rowidx--;
                if (rowidx < 0)
                    rowidx = 0;
            }
            if (e.KeyCode == Keys.Down)
            {
                rowidx++;
                if (rowidx > dataGridView1.Rows.Count - 1)
                    rowidx = dataGridView1.Rows.Count - 1;
            }
        }
        private void cb_api_SelectedIndexChanged(object sender, EventArgs e)
        {
            cb_filter.Items.Clear();
            if (cb_api.SelectedIndex == 0) {
                string[] aladin = { "도서명 + 저자", "도서명", "저자", "출판사" };
                cb_filter.Items.AddRange(aladin);
            }
            else if (cb_api.SelectedIndex == 1) {
                string[] naver = { "도서명", "저자", "출판사", 
                                   "도서명 + 저자", "도서명 + 출판사", "저자 + 출판사", 
                                   "도서명 + 저자 + 출판사" };
                cb_filter.Items.AddRange(naver);
            }
            else if (cb_api.SelectedIndex == 2) {
                string[] daum = { "도서명", "저자", "출판사" };
                cb_filter.Items.AddRange(daum);
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            rowidx = e.RowIndex;
            richTextBox1.Text = dataGridView1.Rows[rowidx].Cells["api_data"].Value.ToString();
        }
        private void Check_ISBN_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!save) {
                if (MessageBox.Show("데이터가 저장되지않았습니다!\n종료하시겠습니까?", "Warning!", MessageBoxButtons.YesNo) == DialogResult.No) {
                    e.Cancel = true;
                }
            }
        }
    }
}