package com.festina;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

public abstract class License 
{
	static boolean isLicension = false;
	
	static String LicenseID;
	static String LicenseIDfromSite;
	public static boolean isFree = false;
	
    public static final String  LICENSE_FILE = "./config/License.ini";
    
    public static void freeLicense()
    {
    	isFree = true;
    }
    
	public static boolean isLicensed()
	{
		return isLicension;
	}
	public static void setLicense(Boolean b)
	{
		isLicension = b;
	}
	public static void checkLicense()
	{
		loadConfig();
		connectSiteLicense();
		if(LicenseID.equalsIgnoreCase(LicenseIDfromSite))
		{
			setLicense(true);
		}
		else
		{
			setLicense(false);
			System.out.println("You are not custmoer.");
			System.exit(0);		
		}
	}
	public static void loadConfig()
	{
		 try 
		 {
			 Properties serverSettings    = new Properties();
			 InputStream is               = new FileInputStream(new File(LICENSE_FILE));
			 serverSettings.load(is);
			 is.close();
				
			 LicenseID = serverSettings.getProperty("LicenseID", "null");

      }
      catch (Exception e)
      {
          e.printStackTrace();
          throw new Error("License file load filed...");
      }
	}
	public static void connectSiteLicense()
	{
		try
		{
			URL LicenseSite = new URL(" http://localhost/"+Config.GAMESERVER_HOSTNAME+".lic "); 
			System.out.println("Trying to license your server...");
			BufferedReader br = new BufferedReader(new InputStreamReader(LicenseSite.openStream()));

			String line = br.readLine();
			LicenseIDfromSite = line;
			br.close(); 
		}
		catch(MalformedURLException me)
		{
			System.err.println("License site connection failed");
			System.err.println(me);
			System.exit(0); 
		}
		catch(IOException ioe)
		{
			System.err.println("Input error: " + ioe); 
		} 
	}
}
