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

namespace FPJ0000.Note
{
    public partial class fNote_Add : Form
    {
        int idx = -1;
        Boolean copyMOde = false;
        Boolean bInit = false;
        string sGUID = string.Empty;
        public fNote_Add(int idx_, Boolean copy = false)
        {
            InitializeComponent();
            this.idx = idx_;
            this.KeyPreview = true;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            foreach (Control ctl in this.panel1.Controls)
            {
                if (ctl.GetType() == typeof(TextBox) || ctl.GetType() == typeof(ComboBox))
                {
                    ctl.KeyDown += ctl_KeyDown;
                }
            }
            copyMOde = copy;
        }

       
        private void fJobReport_Add_Load(object sender, EventArgs e)
        {
            //담당자목록
            var dt_users = FCOMMON.DBM.getUserTable();// getGroupList("name + '(' + id + ')'", "Users", "[level] > 0 and [level] < 10", false, false);
            this.cmbUser.DisplayMember = "dispName";
            this.cmbUser.ValueMember = "id";
            this.cmbUser.DataSource = dt_users;
            if (FCOMMON.info.Login.level < 5) cmbUser.Enabled = false;


            //사용자목록
            //해당 자료를 불러온다.
            if (this.idx == -1)
            {
                //신규추가임
                this.dtPdate.Value = DateTime.Now;
                cmbUser.SelectedValue = FCOMMON.info.Login.no;
                checkBox1.Checked = false;
                richTextBoxEx1.Text = string.Empty;
                sGUID = string.Empty;
            }
            else
            {
                var db = new EEEntities();
                var dr = db.EETGW_Note.Where(t => t.idx == this.idx).FirstOrDefault();
                dtPdate.Value = DateTime.Parse(dr.pdate);
                cmbUser.SelectedValue = dr.uid;
                checkBox1.Checked = (bool)dr.share;
                tbTitle.Text = dr.title;
                sGUID = dr.guid;

                //내가 작성한 글이 아니면 공유를 지정할 수 없게 한다.
                if (dr.uid != FCOMMON.info.Login.no)
                {
                    checkBox1.Enabled = false;
                }
                    
                if (string.IsNullOrEmpty(dr.description2))
                {
                    this.richTextBoxEx1.Text = dr.description;
                }
                else
                {
                    try
                    {
                        this.richTextBoxEx1.Rtf = dr.description2;
                    }
                    catch (Exception ex)
                    {
                        this.richTextBoxEx1.Text = dr.description;
                    }
                }
            }
            if (sGUID.isEmpty())
                sGUID = Guid.NewGuid().ToString();

            this.Show();
            Application.DoEvents();
            this.richTextBoxEx1.Focus();

            bInit = true;
        }
    //    editform.editor ed;
        void ctl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Control ctl = sender as Control;
                string nm = ctl.Name.ToLower();
                string search = ctl.Text.Trim();

                Console.WriteLine("inner keydown " + nm + ":" + search);

                switch (nm)
                {
                    //case "cmbrequest":

                    //    //요청자가 마지막으로 입력한 자료의 process 를 찾아서 기입해준다.
                    //    var lastprocess = FCOMMON.DBM.getFirstValue("process", "purchase", "request like '%" + this.cmbUser.Text + "%'", "pdate desc");
                    //    if (lastprocess != "") cbProcess.Text = lastprocess;
                    //    tbSID.Focus();
                    //    break;
                    case "tbdescription":
                        if (e.Control)
                        {
                            btSave.Focus();
                        }
                        break;
                    
                    default:
                        SendKeys.Send("{TAB}");
                        break;
                }
            }
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FCM0000.fSelectDate f = new FCM0000.fSelectDate(this.dtPdate.Value.ToShortDateString());
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            dtPdate.Value = f.dtSelect;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Invalidate();
          
            if (cmbUser.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("담당자가 선택되지 않았습니다.");
                cmbUser.Focus();
                return;
            }

            //바로저장한다.
            var db = new EEEntities();
            if(idx == -1)
            {
                //신규
                var dr = new EETGW_Note();
                dr.wuid = FCOMMON.info.Login.no;
                dr.wdate = DateTime.Now;
                dr.pdate = dtPdate.Value.ToShortDateString();
                dr.uid = cmbUser.SelectedValue.ToString();
                dr.description = richTextBoxEx1.Text;
                dr.description2 = richTextBoxEx1.Rtf;
                dr.share = checkBox1.Checked;
                dr.title = tbTitle.Text;
                dr.guid = this.sGUID;
                dr.gcode = FCOMMON.info.Login.gcode;
                db.EETGW_Note.Add(dr);
                db.SaveChanges();

            }
            else
            {
                //기존
                var dr = db.EETGW_Note.Where(t => t.idx == this.idx).FirstOrDefault();
                if(dr != null)
                {
                    dr.wuid = FCOMMON.info.Login.no;
                    dr.wdate = DateTime.Now;
                    dr.pdate = dtPdate.Value.ToShortDateString();
                    dr.uid = cmbUser.SelectedValue.ToString();
                    dr.description = richTextBoxEx1.Text;
                    dr.description2 = richTextBoxEx1.Rtf;
                    dr.share = checkBox1.Checked;
                    dr.guid = this.sGUID;
                    dr.title = tbTitle.Text;
                    db.SaveChanges();
                }
            }
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

       
        private void dtPdate_ValueChanged(object sender, EventArgs e)
        {
            var myCI = new System.Globalization.CultureInfo("ko-KR");
            var myCal = myCI.Calendar;
            var myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
            var dat = myCal.GetWeekOfYear(dtPdate.Value, myCWR, myFirstDOW);
            tbWW.Text = "ww" + dat.ToString();

        }
       
        private void cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            var serverpath = Properties.Settings.Default.SharePath; // @"\\10.131.32.29\Data\Project";
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }

            var path = serverpath + "\\Note\\"  + this.sGUID;
            if (System.IO.Directory.Exists(path) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                catch (Exception eX)
                {
                    FCOMMON.Util.MsgE("프로젝트 저장소 생성실패\n" + eX.Message);
                    return;
                }
            } 
            FCOMMON.Util.RunExplorer(path);
        }
    }
}
