using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace XMLExtractor
{
    class REP_IMM_MON_Template
    {
        public int idREP_IMM_MON_Template { get; set; }
        public int idTemplateStrutturaModello { get; set; } 
        public int isActive { get; set; }
        public string altro { get; set; }

        public REP_IMM_MON_Template(int idREP_IMM_MON_Template, int idTemplateStrutturaModello, int isActive, string altro)
        {
            this.altro = altro;
            this.isActive = isActive;
            this.idREP_IMM_MON_Template = idREP_IMM_MON_Template;
            this.idTemplateStrutturaModello = idTemplateStrutturaModello;
            Utility.ID_REP_IMM_MON_TEMPLATE++;
        }

        public void writeDB(SqlConnection conn)
        {
            bool insertInto = true;
            int idTemplateStrutturaModello;
            if ((idTemplateStrutturaModello = this.isPresent(conn)) != 0)
                insertInto = false;

            if(insertInto) {
                //  Creo riga
                SqlCommand insCommand = new SqlCommand("INSERT into REP_IMM_MON_Template (idREP_IMM_MON_Template, " +
                    "idTemplateStrutturaModelli, isActive, altro) VALUES (@idREP_IMM_MON_Template, @idTemplateStrutturaModelli, " +
                    "@isActive, @altro)", conn);
                insCommand.Parameters.AddWithValue("@idREP_IMM_MON_Template", this.idREP_IMM_MON_Template);
                insCommand.Parameters.AddWithValue("@idTemplateStrutturaModelli", this.idTemplateStrutturaModello);
                insCommand.Parameters.AddWithValue("@isActive", 1);
                insCommand.Parameters.AddWithValue("@altro", "");
                insCommand.ExecuteNonQuery();       
            }
        }

        public int isPresent(SqlConnection conn) {

            string sqlCommand = "idTemplateStrutturaModelli = @idTemplateStrutturaModelli";
            SqlCommand cmd = new SqlCommand("SELECT idREP_IMM_MON_TEMPLATE from REP_IMM_MON_Template WHERE " + sqlCommand, conn);
            cmd.Parameters.AddWithValue("@idTemplateStrutturaModelli", this.idTemplateStrutturaModello);

            return cmd.ExecuteScalar() != null ? Convert.ToInt32(cmd.ExecuteScalar() ): 0;     
        }

    }

}
