using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;


namespace Baza_Reklam
{
    public partial class ProjectForm : Form
    {

        private int reklamaID;
        private int projektID;
        private bool pro = false;

        Font printFont = new Font("Arial", 10);

        public ProjectForm(int rekId)
        {
            InitializeComponent();
            reklamaID = rekId;
        }

        public ProjectForm(int rekId,int proId)
        {
            InitializeComponent();
            reklamaID = rekId;
            projektID = proId;
            pro = true;
        }

        private void ProjectForm_Load(object sender, EventArgs e)
        {
            if (!ConnString.getConnString().Value.Contains("truck"))
            {
                jezykComboBox.Visible = false;
                label1.Visible = false;
            }
            jezykComboBox.SelectedIndex = 0;

            pRODUKCJATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            reklamaTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
      
            reklamaTableAdapter1.FillByReklamaId(this.rEKLAMADataSet.REKLAMA,this.reklamaID);

            this.rEKLAMADataSet.PRODUKCJA.Clear();
            this.pRODUKCJATableAdapter.FillByReklamaId(this.rEKLAMADataSet.PRODUKCJA, reklamaID);
            pRODUKCJABindingSource.DataSource = this.rEKLAMADataSet;

            if (pRODUKCJABindingSource.List.Count == 0)
            {
                dodajNowyProjekt(reklamaID);
            }

            if (pro)
            {
                while ( Convert.ToInt32(((DataRowView)pRODUKCJABindingSource.Current)["ID"])!=projektID){
                    pRODUKCJABindingSource.MoveNext();
                }
            }
            else
            {
                pRODUKCJABindingSource.MoveLast();
            }    

        }

        public void dodajNowyProjekt(int rekID)
        {
           // this.reklamaID = rekID;
             
            REKLAMADataSet.REKLAMARow row = this.rEKLAMADataSet.REKLAMA.FindByReklamaID(this.reklamaID);

            int emisja = piewrszaEmisja(reklamaID);
       
            DataView datatable = (DataView)this.pRODUKCJABindingSource.List;
            
            DataRowView row2 = datatable.AddNew();                       
                      
            //dane z zamowienia
            row2["NAZWA_ZAMOWIENIA"] = row["Id reklamy"];
            row2["moduł"] = row["MOD_TYP"];
            row2["reklamaId"] = this.reklamaID;
            row2["szer"] = row["SZER"];
            row2["wys"] = row["WYS"];
            row2["kolor"] = row["KOLOR"];
            row2["lokalizacja"] = row["strona"];
            row2["dataemisji"] = emisja;
            row2["AGENT"] = User.getUser().Login;
            row2["DATA_AGENT"] = DateTime.Now;

            if (DateTime.Today.DayOfWeek == DayOfWeek.Thursday)
            {
                row2["ZAMAWIAM_NA"] = DateTime.Today.AddDays(4);
            }
            else if (DateTime.Today.DayOfWeek == DayOfWeek.Friday)
            {
                row2["ZAMAWIAM_NA"] = DateTime.Today.AddDays(3);
            }
            else
            {
                row2["ZAMAWIAM_NA"] = DateTime.Today.AddDays(2);
            }
           
            dodajButton.Enabled = true;

            pRODUKCJABindingSource.EndEdit();
            pRODUKCJABindingSource.MoveLast();

        }


        private void dodajButton_Click(object sender, EventArgs e)
        {
            pRODUKCJABindingSource.EndEdit();
            pRODUKCJATableAdapter.Update(this.rEKLAMADataSet.PRODUKCJA);
            
            Close();
        }

        /// <summary>
        /// Blokuje pola w zależności od stanu i uprawnień.
        /// </summary>
        private void pRODUKCJABindingSource_CurrentChanged(object sender, EventArgs e)
        {
            DataRowView row = (DataRowView)pRODUKCJABindingSource.Current;

            wymiaryLabel.Text = Utils.pobierzSzerModulu(row["moduł"].ToString()).ToString() +
                " x " + Utils.pobierzWysModulu(row["moduł"].ToString()).ToString();

            if (row["stan"].ToString() == "ZAMAWIAM")
            {
                dodajButton.Enabled = true;
                tYP_PROJEKTUComboBox.Enabled = true;
                zAMAWIAM_NADateTimePicker.Enabled = true;
                pRIORYTETComboBox.Enabled = true;

                oPISTextBox.ReadOnly = false;
                uwagiTextBox.ReadOnly = false;
                path_to_materialTextBox.ReadOnly = false;
                dataEmisjiTextBox.ReadOnly = false;
                lokalizacjaTextBox.ReadOnly = false;
                path_to_materialTextBox.ReadOnly = false;

                usunButton.Enabled = (User.getUser().Symbol_agenta.ToLower() == row["agent"].ToString().ToLower() ?
                    true : false) | User.getUser().St_produkcja;
            }
            else
            {
                dodajButton.Enabled = false | User.getUser().St_produkcja;
                tYP_PROJEKTUComboBox.Enabled = false | User.getUser().St_produkcja;
                zAMAWIAM_NADateTimePicker.Enabled = false | User.getUser().St_produkcja;
                pRIORYTETComboBox.Enabled = false | User.getUser().St_produkcja;
                
                lokalizacjaTextBox.ReadOnly = true & !User.getUser().St_produkcja;
                oPISTextBox.ReadOnly = true & !User.getUser().St_produkcja;
                uwagiTextBox.ReadOnly = true & !User.getUser().St_produkcja;
                path_to_materialTextBox.ReadOnly = true & !User.getUser().St_produkcja;
                dataEmisjiTextBox.ReadOnly = true & !User.getUser().St_produkcja;

                usunButton.Enabled = User.getUser().St_kierownik;
            }

        }

        private void anulujButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Wyszukuje nr pierwszej emisji...
        /// </summary>
        private int piewrszaEmisja(int reklamaId) {

            SqlConnection conn = new SqlConnection(
                ConnString.getConnString().Value);


            SqlCommand command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.CommandText = "select min([Nr Wydania]) from dbo.[UKAŻE SIĘ W NR] where ReklamaId = @param ";
            command.Parameters.AddWithValue("@param",reklamaID);
            command.Connection = conn;

            int emisja = 0;

            conn.Open();
            try
            {
                emisja = Convert.ToInt16(command.ExecuteScalar());
            }
            catch (Exception e1)
            {
                MessageBox.Show("W zamówieniu nie wskazano emisji");
            }
            conn.Close();

            return emisja;
        }
              
        private void drukujProjektButton_Click(object sender, EventArgs e)
        {            
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                printDoc.PrinterSettings = printDialog.PrinterSettings;
                printDoc.PrintPage += new PrintPageEventHandler(Renderuj2);
                printDoc.Print();    
            }
        }

        /// <summary>
        /// Przerysowuje kontrolkę na wydruk.
        /// </summary>
        private void Renderuj2(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {            
            int leftMargin = ev.MarginBounds.Left;
            int topMargin = ev.MarginBounds.Left;
            
            ev.Graphics.DrawRectangle(new Pen(Color.Gray), leftMargin, topMargin, this.Width, this.Height);

            foreach (Control c in this.Controls) {
                
                string controlType = c.GetType().ToString().Substring(c.GetType().ToString().LastIndexOf(".") + 1);
                
                switch (controlType) { 
                    case "TextBox":
                        TextBox t = (TextBox)c;
                        ev.Graphics.DrawRectangle(new Pen(Color.Gray), t.Left + leftMargin, t.Top + topMargin, t.Width, t.Height);
                        ev.Graphics.DrawString(t.Text, t.Font, new SolidBrush(t.ForeColor), new RectangleF(t.Left + leftMargin + 2, t.Top + topMargin + 1, t.Width + 2, t.Height - 2), new StringFormat());
                        break;
                    case "Label":
                        Label l = (Label)c;
                        ev.Graphics.DrawString(l.Text, l.Font, new SolidBrush(l.ForeColor), l.Left + leftMargin, l.Top + topMargin + l.Height / 2 - ev.Graphics.MeasureString("a", l.Font).Height / 2, new StringFormat());
                        break;
                    case "ComboBox":
                        ComboBox cb = (ComboBox)c;
                        ev.Graphics.DrawRectangle(new Pen(Color.LightGray), cb.Left + leftMargin, cb.Top + topMargin, cb.Width, cb.Height);
                        ev.Graphics.DrawString(cb.Text, cb.Font, new SolidBrush(cb.ForeColor), cb.Left + leftMargin + 2, cb.Top + topMargin+ cb.Height / 2 - ev.Graphics.MeasureString("a", cb.Font).Height / 2, new StringFormat());
                        break;
                    case "DateTimePicker":
                        DateTimePicker dp = (DateTimePicker)c;
                        ev.Graphics.DrawRectangle(new Pen(Color.LightGray), dp.Left + leftMargin, dp.Top + topMargin, dp.Width, dp.Height);
                        ev.Graphics.DrawString(dp.Text, dp.Font, new SolidBrush(dp.ForeColor), dp.Left + leftMargin + 2, dp.Top + topMargin + dp.Height / 2 - ev.Graphics.MeasureString("a", dp.Font).Height / 2, new StringFormat());
                        break;
                    default:
                        break;
                }
            }
        }

        private void dodajNowyButton_Click(object sender, EventArgs e)
        {
            dodajNowyProjekt(reklamaID);
        }

        private void usunButton_Click(object sender, EventArgs e)
        {
            pRODUKCJABindingSource.RemoveCurrent();
        }

        private void modułComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            pRODUKCJABindingSource.EndEdit();
            DataRowView row = (DataRowView)pRODUKCJABindingSource.Current;
            row["moduł"] = row["moduł"];
            pRODUKCJABindingSource.EndEdit();
        }

        private void zAMAWIAM_NADateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            if (zAMAWIAM_NADateTimePicker.Value.DayOfWeek == DayOfWeek.Saturday)
            {
                zAMAWIAM_NADateTimePicker.Value = zAMAWIAM_NADateTimePicker.Value.AddDays(-1);
                MessageBox.Show("WEEKEND! Wybierz inny dzień");
                return;
            }

            if (zAMAWIAM_NADateTimePicker.Value.DayOfWeek == DayOfWeek.Sunday)
            {
                zAMAWIAM_NADateTimePicker.Value = zAMAWIAM_NADateTimePicker.Value.AddDays(-2);
                MessageBox.Show("WEEKEND! Wybierz inny dzień");
                return;
            }
       
        }
    }
}