/*
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*
  <file> UlsContext.h </file>
  <brief>
  </brief>
  <author>
    Stanley Hong <link2next@gmail.com>, Oct. 2017.
  </author>
*/
#pragma once

#include "UlsFactory.h"

using namespace System;

namespace uls {
	namespace polaris {
		public ref class UlsContext {
			bool isDisposed;
			UlsFactory ^uf;

		public:
			delegate void DelegateOnExitProc(Object ^data);
			typedef DelegateOnExitProc ^OnExitProc;

			delegate int DelegateOptProc(int opt, String ^optarg);
			typedef DelegateOptProc ^OptProc;

		private:
			ref struct onexit_entry_t {
				Object ^data;
				OnExitProc onexit;
				onexit_entry_t  ^next;
			};
			typedef onexit_entry_t ^onexit_entry_ptr_t;

			onexit_entry_t ^onexit_list;

			// <brief>
			// The format string consisting of permitted option chars</parm>
			// </brief>
			String ^optfmt;

			void initUlsContext();
			int getopts_chars(array<String ^> ^args, const char *optfmt_cstr, OptProc proc);

		public:
			UlsContext();
			UlsContext(String ^optfmt_str);
			virtual ~UlsContext();

			// <brief>
			// A C++/CLI brief version of atexit()
			// </brief>
			void registerProcOnExit(OnExitProc proc, Object^ data);

			// <brief>
			// A C++/CLI brief version of atexit()
			// </brief>
			void flushProcsOnExit();

			// <brief>
			// A C++/CLI brief version of getopt()
			// </brief>
			// <parm name="args">Array of Strings</parm>
			// <parm name="proc">The procedure of option character and 'optarg'</parm>
			// <return>the index 'i0' is the index of the first non-option, argument,
			// i.e., args[i0] doesn't start with the char '-'.</return>
			int parseOpts(array<String ^> ^args, OptProc proc);
		};
	}
}
