/*********************************************************************************************
 * Copyright 2004 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: SerialNo.cs $     $Revision: 7 $
 * $Author: Jsj $   $Date: 12/06/07 3:32p $
 *
 * $History: SerialNo.cs $
 * 
 * *****************  Version 7  *****************
 * User: Jsj          Date: 12/06/07   Time: 3:32p
 * Updated in $/LibSource/Utils
 * turn on backgrounds for point beach
 * 
 * *****************  Version 6  *****************
 * User: Jsj          Date: 7/18/06    Time: 11:40a
 * Updated in $/LibSource/Utils
 * fixed parse of plant name from SERIAL.NO file
 * 
 * *****************  Version 5  *****************
 * User: Jsj          Date: 6/29/06    Time: 1:38p
 * Updated in $/LibSource/Utils
 * turned on enhanced backgrounds for byron and braidwood
 * 
 * *****************  Version 4  *****************
 * User: Jsj          Date: 6/29/06    Time: 1:27p
 * Updated in $/LibSource/Utils
 * turned on Deviations for byron and braidwood
 * 
 * *****************  Version 3  *****************
 * User: Jsj          Date: 5/17/05    Time: 11:53a
 * Updated in $/LibSource/Utils
 * cleanup
 * 
 * *****************  Version 2  *****************
 * User: Kathy        Date: 4/12/05    Time: 1:00p
 * Updated in $/LibSource/Utils
 * B2005-019: bad serial num message
 * 
 * *****************  Version 1  *****************
 * User: Kathy        Date: 7/27/04    Time: 8:34a
 * Created in $/LibSource/Utils
 *********************************************************************************************/

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Utils
{
	/// <summary>
	/// Summary description for SerialNo.
	/// </summary>
	public class SerialNo
	{
		private string sernofile;
		public int SerialNum;
		private string SerialNumTitle;
		private static byte sum =0xcf;// used in serial number code (nextchar)

		public enum SN_Flags
		{
			SN_NETWORK_ON			=0x0001,
			SN_BACKGROUND_ON		=0x0002,
			SN_DEVIATION_ON			=0x0004,
			SN_CHECKLISTEXPORT_ON	=0x0008,
			SN_REVISIONFUNCTION_ON	=0x0010,
			SN_ONLYAPPROVEONCE_ON	=0x0020,
			SN_BGEPLANTWIDEOPT_ON	=0x0040,
			SN_REVISESTRIPPC_ON		=0x0080,
			SN_PROCCOMMENT_ON		=0x0400,
			SN_REMOVECHGID_ON		=0x0800,
			SN_OPTIONALACCEDIT_ON	=0x1000,
			SN_TEMPCHANGE_ON		=0X2000,
			SN_VOLIANONLY_ON		=0x8000		
		};

		public SN_Flags[] SerialNumberOptionsByPlant=
		{
			/* 0 Volian Enterprises, Inc.                                     */ (SN_Flags)0xFFFF,
			/* 1 Entergy Nuclear Northeast - Indian Point Unit 2			  */ SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_NETWORK_ON,
			/* 2 Virginia Power - Surry (1A)                                  */ SN_Flags.SN_NETWORK_ON,
			/* 3 Virginia Power - North Anna                                  */ SN_Flags.SN_DEVIATION_ON|SN_Flags.SN_NETWORK_ON,
			/* 4 Northern States Power - Prairie Island                       */ SN_Flags.SN_DEVIATION_ON,
			/* 5 American Electric Power - D. C. Cook - AOPs                  */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/* 6 Wisconsin Electric Power - Point Beach                       */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/* 7 Rochester Gas and Electric Corp. - Ginna                     */ SN_Flags.SN_BACKGROUND_ON,
			/* 8 TUEC - Comanche Peak                                         */ 0,
			/* 9 Entergy Nuclear Northeast - Indian Point Unit 3              */ SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_NETWORK_ON,
			/*10 Maine Yankee Atomic Power Company - Maine Yankee             */ 0,
			/*11 Yankee Atomic Electric - Yankee Rowe                         */ 0,
			/*12 Wisconsin Public Service Corp.- Kewaunee                     */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/*13 Wisconsin Public Service Corp.- Kewaunee Operating Procedures*/ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/*14 South Carolina Gas and Electric - V.C. Summer                */ 0,
			/*15 Louisiana Power and Light - Waterford                        */ 0,
			/*16 Pacific Gas and Electric - Diablo Canyon                     */ SN_Flags.SN_OPTIONALACCEDIT_ON,
			/*17 Southern California Edison - San Onofre                      */ 0,
			/*18 Carolina Power and Light - Robinson                          */ SN_Flags.SN_NETWORK_ON,/*|SN_BACKGROUND_ON|SN_DEVIATION_ON, */
			/*19 Arkansas Nuclear One - Unit 1                                */ 0,
			/*20 Arkansas Nuclear One - Unit 2                                */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_ONLYAPPROVEONCE_ON|SN_Flags.SN_REVISIONFUNCTION_ON|SN_Flags.SN_REVISESTRIPPC_ON|SN_Flags.SN_PROCCOMMENT_ON,
			/*21 Southern Nuclear Operating Company - Vogtle                  */ SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_DEVIATION_ON,
			/*22 Florida Power and Light - Turkey Point (Unit 3)              */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_DEVIATION_ON|SN_Flags.SN_BACKGROUND_ON,
			/*23 Houston Lighting & Power Company - South Texas               */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/*24 Carolina Power & Light - Shearon Harris                      */ 0,
			/*25 Virginia Power - EPIP                                        */ SN_Flags.SN_NETWORK_ON,
			/*26 Wolf Creek Nuclear Operating Corp. - Wolf Creek              */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_OPTIONALACCEDIT_ON|SN_Flags.SN_TEMPCHANGE_ON|SN_Flags.SN_CHECKLISTEXPORT_ON,
			/*27 Duke Power - Catawba                                         */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_DEVIATION_ON,
			/*28 Duke Power - McGuire                                         */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_DEVIATION_ON,
			/*29 Exelon Nuclear - Braidwood                                   */ SN_Flags.SN_NETWORK_ON | SN_Flags.SN_BACKGROUND_ON | SN_Flags.SN_DEVIATION_ON,
			/*30 Exelon Nuclear - Byron                                       */ SN_Flags.SN_NETWORK_ON | SN_Flags.SN_BACKGROUND_ON | SN_Flags.SN_DEVIATION_ON,
			/*31 Virginia Power - Innsbrook                                   */ SN_Flags.SN_NETWORK_ON,
			/*32 Constellation Energy Group - Calvert Cliffs                  */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_REVISIONFUNCTION_ON|SN_Flags.SN_ONLYAPPROVEONCE_ON|SN_Flags.SN_BGEPLANTWIDEOPT_ON|SN_Flags.SN_OPTIONALACCEDIT_ON|SN_Flags.SN_REMOVECHGID_ON,
			/*33 American Electric Power - D. C. Cook - EOPs                  */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON,
			/*34 American Electric Power - D. C. Cook - Training              */ 0,
			/*35 North Atlantic Energy Service Corp. - Seabrook Nuclear Plant */ SN_Flags.SN_TEMPCHANGE_ON,
			/*36 Entergy - River Bend Nuclear Station                         */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_REVISIONFUNCTION_ON,
			/*37 Southern Nuclear Operating Company - Farley Nuclear Plant    */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON|SN_Flags.SN_DEVIATION_ON,
			/*38 AmerenUE - Callaway Plant					                  */ SN_Flags.SN_NETWORK_ON|SN_Flags.SN_BACKGROUND_ON
		};

		public SerialNo(string isernofile,string ucfgpath, UserRunTime usrRT, bool DemoMode)
		{
			sernofile = isernofile;
			PrivateProfile ppCfg;
			string sn;
//			byte xor=0xCF;
			ppCfg = new PrivateProfile(ucfgpath);
			//			sn=ppCfg.Attr("/ini/section[@name='override']/param[@name='SN']/@value");
			sn=ppCfg.Attr("override","SN");
			if (sn!=null && sn!="")
			{
				int indx = 0;
				if ((indx = sn.IndexOf(";",0,sn.Length))>0)
					SerialNum=System.Convert.ToInt32(sn.Substring(0,indx));
				else
					SerialNum=System.Convert.ToInt32(sn);
				if (SerialNum>SerialNumberOptionsByPlant.Length)
				{
					MessageBox.Show("Serial number in " + ucfgpath + " is invalid. Demo mode will be used","VE-PROMS");
					SerialNum=-1;					
				}
				SerialNumTitle="Override";
				return;
			}

			ppCfg=null;
			SerialNum = -1;
			if (DemoMode || !File.Exists(usrRT.ExeAdjust(sernofile)))
			{
				// no serial number file, put into demo mode.
				SerialNumTitle = "Demo Mode";
				//				MessageBox.Show("No Serial Number. Defaulting to Working Demo Mode.\n\nTo purchase VE-PROMS, contact Volian Enterorices Inc.\n\nPhone: (724) 335-3744\n\nEmail: VEPROMS@VOLIAN.COM\n\nSerial Number Warning"); 
				if (DemoMode)
				{
					MessageBox.Show("Thank you for trying our VE-PROMS Working Demo.\n\n"+
						"To purchase VE-PROMS, contact Volian Enterprises, Inc.\n\n"+
						"Phone:  (724) 335-3744\n\n"+
						"Email:  VolianEnterprises@volian.com",
						"VE-PROMS Working Demo");
				}
				else
				{
					MessageBox.Show("No Serial Number.  Defaulting to Working Demo Mode.\n\n"+
						"To purchase VE-PROMS, contact Volian Enterprises, Inc.\n\n"+
						"Phone:  (724) 335-3744\n\n"+
						"Email:  VolianEnterprises@volian.com",
						"Serial Number Warning");
				}
				return;
			}

			// open file & read in serial number
			int i;
			byte j;
			FileStream fssn = null;
			BinaryReader brsn = null;
			byte xor=0xCF;
//			sum=0xcf;
			try
			{
				fssn = new FileStream(usrRT.ExeAdjust(sernofile),FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
				brsn = new BinaryReader(fssn);
				int length = (int)fssn.Length-1024;
				for (i=0;i<1024;i++)
				{
					j = nextchar(brsn);
					xor ^= (byte)j;
					if (j==0xCF)
					{
						if (SerialNum != -1) return;
						SerialNum=i;
					}
				}
				if (SerialNum == -1)
				{
					SerialNumTitle = "Demo Mode";
//					MessageBox.Show("No Serial Number. Defaulting to Working Demo Mode.\n\nTo purchase VE-PROMS, contact Volian Enterorices Inc.\n\nPhone: (724) 335-3744\n\nEmail: VEPROMS@VOLIAN.COM\n\nSerial Number Warning","VE-PROMS"); 
					MessageBox.Show("No Serial Number.  Defaulting to Working Demo Mode.\n\n"+
						"To purchase VE-PROMS, contact Volian Enterprises, Inc.\n\n"+
						"Phone:  (724) 335-3744\n\n"+
						"Email:  VolianEnterprises@volian.com",
						"Serial Number Warning");
					return;
				}
				// Just read past this byte. At this point we already
				// have a serial number.  We now just want to get the
				// description text (usually plant/utility name) associated
				// with the serial number.
				j = nextchar(brsn);
//
//	This was always failing.  Could not find a reason why. Appears that
//  the Exclusive OR arithmatic is a little different in .NET.  The
//  nextchar() funtion seems to be returning the correct values.
//
//				if (j!=xor)
//				{
//					if (brsn!=null) brsn.Close();
//					if (fssn!=null) fssn.Close();
//					return;
//				}
				char [] title = new char[length];
				i=0;
				while((--length) > 0 && (j=nextchar(brsn))!=0xFF)
				{
					title[i++] = (char)j;
				}
				SerialNumTitle = new string(title);
				// remove the serial number at the beginning of the title
				// - we didn't need to do this - jsj 7/18/2006
//				SerialNumTitle = SerialNumTitle.Substring(SerialNumTitle.IndexOf(' ')+1);
			}
			catch(Exception e)
			{
				MessageBox.Show(e.Message,"Serial Number Error");
				return;
			}
			if (brsn!=null) brsn.Close();
			if (fssn!=null) fssn.Close();
		}

		private byte nextchar(BinaryReader br)
		{
			byte retval = 0xFF; // unsigned -1
			try 
			{
				byte nxt;
				retval = br.ReadByte();
				if(retval != 0xFF)
				{
					nxt=retval;
					retval=(byte)((nxt-sum) & 0xFF);
					sum=(byte)(((nxt<<1) & 0xFE) | ((nxt>>7) & 0x1));
				}
			}
			catch(Exception e)
			{
//				MessageBox.Show(e.Message);
				return retval;
			}

			return retval;
		}

		public uint GetSNOption(uint a) 
		{
			if (SerialNum == -1)
				return 0;
			else
				return ((uint)SerialNumberOptionsByPlant[SerialNum]&(uint)a);
		}

		public string SerialNumberString
		{
			get
			{
				string rtnstr  = "";
				if (SerialNum == -1) // demo
					rtnstr  = "Thank you for trying VE-PROMS";
				else
					rtnstr  = "Serial Number:  " + SerialNum.ToString();

				return rtnstr;
			}
		}

		public string SerialNumberTitleString
		{
			get
			{
				return SerialNumTitle;
			}
		}
	}
}
