using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;

using core.BusinessObject;
using Sky.Darkness.Commons.DataAccess;
using Sky.Darkness.Commons.Util;

/// <summary>
/// PaperDataAccess 的摘要说明
/// </summary>
public class SubjectDataAccess
{
    private static readonly string _connectionString = string.Empty;

    public DataSet SelectCourseName()
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(_connectionString);
        string sql = "select CourseName from course";
        SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter(sql, con);
        objSqlDataAdapter.Fill(ds, "courseName");
        return ds;
    }

    public DataSet SelectType()
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(_connectionString);
        string sql = "select themeType from theme";
        SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter(sql, con);
        objSqlDataAdapter.Fill(ds, "typeName");
        return ds;
    }

    public DataSet SearchSubject(string subjectID)
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(_connectionString);
        string sql = "select course.courseName,theme.themeType,subjectContent,subjectAnswer,courseChapter,difficultFactor from course,theme,subjectStoreRoom " +
            "where course.courseID=subjectStoreRoom.courseID and theme.themeID=subjectStoreRoom.themeID " +
            "and subjectStoreRoom.subjectID=" + subjectID;
        SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter(sql, con);
        objSqlDataAdapter.Fill(ds, "subject");
        return ds;
    }

 
    /// <summary>
    /// Selects all objects from the database
    /// </summary>
    /// <param name="start">start point</param>
    /// <param name="limit">the total count you need to search</param>
    /// <returns></returns>
    public List<Subject> SearchPaging(int start, int limit)
    {
        return Search(start,limit,"","","");
    }

    public List<Subject> Search(string courseName, string themeType, string courseChapter)
    {
        return Search(0,10,courseName,themeType,courseChapter);
    }

    public List<Subject> SearchTitles(int paperId)
    {
        string strSqlSubjects = "select subjectID,course.courseName,theme.themeType,subjectContent,subjectAnswer,courseChapter,difficultFactor,subjectStoreRoom.id from course,theme,subjectStoreRoom " +
            "where course.courseID=subjectStoreRoom.courseID and theme.themeID=subjectStoreRoom.themeID ";
        strSqlSubjects += " AND(";

        /**
         * 取出该试卷中已经存在的题目
         * ,存放在 arrTitleNumbers中
         */
        string strSelectTitles = "SELECT titles FROM paperInformation WHERE paperId=" + paperId;
        DataSet dsTitles = SqlHelper.FillDataSet(strSelectTitles, null, CommandType.Text);
        string strTitles = dsTitles.Tables[0].Rows[0][0].ToString();

        string[] arrTitles = strTitles.Split(';');
        int[] arrTitleNumbers = null;
        for (int i = 0; i < arrTitles.Length; i++)
        {
            if ("".Equals(arrTitles[i].Trim()))
                continue;

            string[] arrTitleDetails = arrTitles[i].Split(':');
            string[] strTitleNumbers = arrTitleDetails[1].Split(',');
            arrTitleNumbers = new int[strTitleNumbers.Length];
            for (int j = 0; j < strTitleNumbers.Length; j++)
            {
                strSqlSubjects += " subjectID=" + strTitleNumbers[j] + " OR ";
            }
        }
        strSqlSubjects = strSqlSubjects.Substring(0,strSqlSubjects.Length-3);
        strSqlSubjects += ")";

        return Search(strSqlSubjects);
    }

    public List<Subject> Search(string  strSql)
    {
        // Create Classes collection
        List<Subject> colSubject = new List<Subject>();

        // Create connection
        SqlConnection con = new SqlConnection(_connectionString);

        // Create command
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = strSql;

        // Execute command
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                string subId = reader["subjectID"].ToString().Trim();
                string curName = reader["courseName"].ToString().Trim();
                string theType = reader["themeType"].ToString().Trim();
                string subjectCountent = reader["subjectContent"].ToString().Trim();
                string subjectAnswer = reader["subjectAnswer"].ToString().Trim();
                string curChapter = reader["courseChapter"].ToString().Trim();
                string difficultFactor = reader["difficultFactor"].ToString().Trim();
                int id = (int)reader["id"];
                colSubject.Add(new Subject(
                    subId,
                    curName,
                    theType,
                    subjectCountent,
                    subjectAnswer,
                    curChapter,
                    difficultFactor, id));
            }
        }
        return colSubject;
    }

    public List<Subject> Search(int start,int limit,string courseName,string themeType,string courseChapter)
    {
        string strSql = "select TOP " + limit + " subjectID,course.courseName,theme.themeType,subjectContent,subjectAnswer,courseChapter,difficultFactor,subjectStoreRoom.id from course,theme,subjectStoreRoom " +
        "where course.courseID=subjectStoreRoom.courseID and theme.themeID=subjectStoreRoom.themeID " +
        "and course.courseName like '%" + courseName + "%' and theme.themeType like '%" + themeType + "%' and courseChapter like '%" + courseChapter + "%'" + " AND subjectStoreRoom.subjectID NOT IN(SELECT TOP " + start
        + " subjectID FROM course,theme,subjectStoreRoom " +
        "where course.courseID=subjectStoreRoom.courseID and theme.themeID=subjectStoreRoom.themeID " +
        "and course.courseName like '%" + courseName + "%' and theme.themeType like '%" + themeType + "%' and courseChapter like '%" + courseChapter + "%'"
        + " ORDER BY subjectID ASC) ORDER BY subjectID ASC";

        return Search(strSql);
    }

    public int GetAllCount()
    {
        return GetAllCount("","");
    }

    public int GetAllCount(string courseName, string themeType)
    {
        string sqlStr = "SELECT COUNT(*) FROM course,theme,subjectStoreRoom " +
            "where course.courseID=subjectStoreRoom.courseID and theme.themeID=subjectStoreRoom.themeID " +
            "and course.courseName like '%" + courseName + "%' and theme.themeType like '%" + themeType + "%' ";

        return (int)SqlHelper.ExecuteScalar(sqlStr);
    }

    public void AddSubjectType(string explain,string type)
    {
        SqlConnection con = new SqlConnection(_connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO theme(themeExplain,themeType) values(@themeExplain,@themeType)";
        cmd.Parameters.AddWithValue("@themeExplain",explain);
        cmd.Parameters.AddWithValue("@themeType",type);
        using (con)
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }

    /// <summary>
    /// Inserts a new Subject into the database
    /// </summary>
    /// <param name="newClasses">Subject</param>
    public int Insert(Subject newSubject)
    {
        int count = 0;
        try
        {
            // Create connection
            SqlConnection con = new SqlConnection(_connectionString);

            // Create command
            SqlCommand cmd = new SqlCommand();

            string courseName = newSubject.CourseName;
            string type = newSubject.ThemeName;
            string sql = "select courseID,themeID from course, theme where courseName='" + courseName + "' and themeType='" + type + "'";
            DataSet ds = new DataSet();
            SqlDataAdapter objAdapter = new SqlDataAdapter(sql, _connectionString);
            objAdapter.Fill(ds, "courseID&themeID");
            string courseID = ds.Tables[0].Rows[0][0].ToString();
            string themeID = ds.Tables[0].Rows[0][1].ToString();
            int maxID = -1;

            sql = "select max(subjectID) as a from subjectStoreRoom";
            cmd.Connection = con;
            cmd.CommandText = sql;
            using (con)
            {
                con.Open();
                SqlDataReader objdr = cmd.ExecuteReader();
                while (objdr.Read())
                {
                    string str_test = objdr["a"].ToString();
                    if (str_test.Equals("") || str_test == null)
                    {
                        maxID++;
                    }
                    else
                        maxID = (int)objdr["a"];
                }
                objdr.Close();
            }
            int subjectID = maxID + 1;
            SqlConnection con1 = new SqlConnection(_connectionString);
            cmd.Connection = con1;
            cmd.CommandText = "INSERT subjectStoreRoom (subjectID,courseID,themeID,subjectContent,subjectAnswer,courseChapter,difficultFactor) "
                                      + "VALUES (@subjectID,@courseID,@themeID,@subjectContent,@subjectAnswer,@courseChapter,@difficultFactor)";


            // Add parameters
            cmd.Parameters.AddWithValue("@subjectID", subjectID);
            cmd.Parameters.AddWithValue("@courseID", courseID);
            cmd.Parameters.AddWithValue("@themeID", themeID);
            cmd.Parameters.AddWithValue("@subjectContent", newSubject.SubjectContent);
            cmd.Parameters.AddWithValue("@subjectAnswer", newSubject.SubjectAnswer);
            cmd.Parameters.AddWithValue("@courseChapter", newSubject.CourseChapter);
            cmd.Parameters.AddWithValue("@difficultFactor", newSubject.DifficultFactor);

            // Execute command
            using (con1)
            {
                con1.Open();
                count=cmd.ExecuteNonQuery();
               
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);

        }

        return count;
    }

        /// <summary>
        /// Updates an existing Subject into the database
        /// </summary>
        /// <param name="classesToUpdate">Subject</param>
    public int Update(Subject subjectToUpdate)
    {
        int count = 0;
        try
        {
            // Create connection
            SqlConnection con = new SqlConnection(_connectionString);

            string courseName = subjectToUpdate.CourseName;
            string type = subjectToUpdate.ThemeName;
            string sql = "select courseID,themeID from course, theme where courseName='" + courseName + "' and themeType='" + type + "'";
            DataSet ds = new DataSet();
            SqlDataAdapter objAdapter = new SqlDataAdapter(sql, _connectionString);
            objAdapter.Fill(ds, "courseID&themeID");
            string courseID = ds.Tables[0].Rows[0][0].ToString();
            string themeID = ds.Tables[0].Rows[0][1].ToString();
            // Create command
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "UPDATE subjectStoreRoom SET courseID=@courseID,themeID=@themeID,subjectContent=@subjectContent,subjectAnswer=@subjectAnswer,courseChapter=@courseChapter,difficultFactor=@difficultFactor  WHERE subjectID=@subjectID";

            // Add parameters
            cmd.Parameters.AddWithValue("@courseID", courseID);
            cmd.Parameters.AddWithValue("@themeID", themeID);
            cmd.Parameters.AddWithValue("@subjectContent", subjectToUpdate.SubjectContent);
            cmd.Parameters.AddWithValue("@subjectAnswer", subjectToUpdate.SubjectAnswer);
            cmd.Parameters.AddWithValue("@courseChapter", subjectToUpdate.CourseChapter);
            cmd.Parameters.AddWithValue("@difficultFactor", subjectToUpdate.DifficultFactor);
            cmd.Parameters.AddWithValue("@subjectID", subjectToUpdate.SubjectID);


            // Execute command
            using (con)
            {
                con.Open();
                count = cmd.ExecuteNonQuery();
            }
        }catch(Exception ex)
        {
            Console.WriteLine(ex.Message);

        }
        return count;
    }

        /// <summary>
        /// Deletes an existing Subject in the database
        /// </summary>
        /// <param name="departmentID">Subject Id</param>
    public int  Delete(Subject subjectToUpdate)
    {
        int count = 0;
        try
        {
            // Create connection
            SqlConnection con = new SqlConnection(_connectionString);

            // Create command
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "DELETE subjectStoreRoom WHERE subjectID=@subjectID";

            // Add parameters
            cmd.Parameters.AddWithValue("@subjectID", subjectToUpdate.SubjectID);

            // Execute command
            using (con)
            {
                con.Open();
                count = cmd.ExecuteNonQuery();
            }

        }catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return count;
    }

    /// <summary>
    /// Initialize the data access layer by
    /// loading the database connection string from 
    /// the Web.Config file
    /// </summary>
    static SubjectDataAccess()
    {
        _connectionString = ConfigurationManager.AppSettings["GlobalConnectionString"];
        if (string.IsNullOrEmpty(_connectionString))
            throw new Exception("No connection string configured in Web.Config file");

    }
}
