using System;
using System.Configuration;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;

namespace SouthSmart.GISService.Infrastructure.Module
{
    public class SDEHelper
    {
        private IWorkspace _workspace;

        /// <summary>
        /// 数据工作空间
        /// </summary>
        public IWorkspace PWorkspace
        {
            get { return _workspace; }
            set { _workspace = value; }
        }

        /// <summary>
        /// 连接SDE数据库
        /// </summary>
        /// <returns></returns>
        public void OpenData ()
        {
            try
            {
                string sdeConnectString = ConfigurationManager.ConnectionStrings["SDEConn"].ConnectionString;

                string[] str = sdeConnectString.Split ( ';' );
                IPropertySet pProperty = new PropertySetClass ();
                pProperty.SetProperty ( "SERVER", str[0].Split ( '=' )[1] );
                pProperty.SetProperty ( "INSTANCE", str[1].Split ( '=' )[1] );
                pProperty.SetProperty ( "DATABASE", str[2].Split ( '=' )[1] );
                pProperty.SetProperty ( "USER", str[3].Split ( '=' )[1] );
                pProperty.SetProperty ( "PASSWORD", str[4].Split ( '=' )[1] );
                pProperty.SetProperty ( "VERSION", str[5].Split ( '=' )[1] );

                IWorkspaceFactory spaceFactory = new SdeWorkspaceFactoryClass ();
                PWorkspace = spaceFactory.Open ( pProperty, 0 );//SDE连接
            }
            catch ( Exception ex )
            {
                throw ex;
            }
        }

        /// <summary>
        /// 打开空间数据表
        /// </summary>
        /// <param name="featureClassName"></param>
        /// <returns></returns>
        public IFeatureClass OpenFeatureClassByName ( string featureClassName )
        {
            if ( PWorkspace != null )
            {
                IFeatureWorkspace featureWorkspace = _workspace as IFeatureWorkspace;
                if ( featureWorkspace != null )
                {
                    IFeatureClass featureclass = featureWorkspace.OpenFeatureClass ( featureClassName );
                    return featureclass;
                }
                else
                {
                    return null;
                }
            }
            else
                throw new Exception ( "您未打开空间数据库工作空间！" );
        }
    }
}