using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using JuSNS.Config;
using System.Drawing;

namespace JuSNS.Common.PicUpload
{
    public class GroupUpload : PicUpload
    {
        private HttpPostedFile _postfile;

        public GroupUpload(HttpPostedFile postfile)
        {
            _postfile = postfile;
            server = PicConfig.GroupServer;
        }
        public override void Start()
        {
            string dir = "";
            dir = PicConfig.GroupDir;
            string path = RootDir + "/" + dir;
            path = HttpContext.Current.Server.MapPath(path);
            int j = 0;
            string fileMainName = GetNewName();
            string fileExtName = GetExt(_postfile.FileName);
            string filename = fileMainName + "." + fileExtName;
            if (_postfile.ContentLength == 0)
            {
                _errmsg = "图片文件太小";
                return;
            }
            if (_postfile.ContentLength > size)
            {
                _errmsg = "图片文件占用内存超过" + (size / 1000) + "KB";
                return;
            }
            if (!AllowExt(fileExtName))
            {
                _errmsg = "图片格式不正确";
                return;
            }
            Array.Resize<int>(ref _Width, j + 1);
            Array.Resize<int>(ref _Height, j + 1);
            Array.Resize<string>(ref _FileName, j + 1);
            Array.Resize<int>(ref _ContentLength, j + 1);
            System.Drawing.Image image = Bitmap.FromStream(_postfile.InputStream);
            _Width[j] = image.Width;
            _Height[j] = image.Height;
            _FileName[j] = filename;
            _ContentLength[j] = _postfile.ContentLength;
            if (string.IsNullOrEmpty(server) || server == "~")
            {
                #region 上传for本地
                Upload up = new Upload();
                up.PostedFile = _postfile;
                up.Extension = fileExtName;
                up.FileLength = up.PostedFile.ContentLength;
                up.FileName = filename;
                up.SavePath = path;
                string err = up.UploadStart();
                if (err.IndexOf('$') != -1)
                {
                    Thumbnail.MakeAllThumbnail(path, filename, 2);
                    _SuccessNum++;
                }
                #endregion
            }
            else
            {
                #region 上传for远程
                byte[] data = new byte[_postfile.ContentLength];
                _postfile.InputStream.Write(data, 0, _postfile.ContentLength);
                int n = UploadService(data, RootDir + "/" + dir + "/" + filename);
                if (n > 0)
                {
                    _SuccessNum++;
                }
                #endregion
            }            
        }
    }
}
