using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Baza_Reklam.pl.admoto.service;
using System.IO;

namespace Baza_Reklam
{
    public partial class OgloszenieWaitForm : Form
    {
        private int _nrWydania;
        private string[] _fotoFileName;
        private string errStr;

        public OgloszenieWaitForm(int nrWydania, string[] fotoFileName)
        {
            InitializeComponent();

            _nrWydania = nrWydania;
            _fotoFileName = fotoFileName;

            //this.DialogResult = DialogResult.Cancel;
        }

        private void OgloszenieWaitForm_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ImportOtoMoto webService = new ImportOtoMoto();

                webService.Authenticate(User.Instance().Login, User.Instance().Password);

                string idReklamy = Path.GetFileNameWithoutExtension(_fotoFileName[0]);

                //wysyłka zdjęć
                int n = 0;
                foreach (string fname in _fotoFileName)
                {
                    if (string.IsNullOrEmpty(fname))
                        continue;

                    FileStream fs = new FileStream(fname, FileMode.OpenOrCreate, FileAccess.Read);
                    Byte[] img = new Byte[fs.Length];
                    fs.Read(img, 0, Convert.ToInt32(fs.Length));
                    webService.PutImage(img, _nrWydania, idReklamy, n);
                    fs.Close();
                    ++n;

                    backgroundWorker1.ReportProgress(n);
                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                errStr = ex.Message;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(errStr))
                MessageBox.Show("Akceptacja ogłoszenie nie została zakończona prowidłowo.\n" + errStr, "Baza reklam", MessageBoxButtons.OK, MessageBoxIcon.Error);

            this.Close();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage <= progressBar1.Maximum)
                progressBar1.Value = e.ProgressPercentage;
        }
    }
}