package com.ericsson.cms.plugins.ta;
import java.net.InetAddress;
import java.text.DecimalFormat;

import com.tandbergtv.metadatamanager.model.Asset;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.title.conf.IAutoFillVariableProvider;

public class AssetIdGenerator implements IAutoFillVariableProvider {
	private static final String IP_LOCALHOST = "127.0.0.1";
	
	@Override
	public String getValue(Title title, Asset asset) {
		return getPrefix(asset) + getNewId();
	}

	private String getPrefix(Asset asset) {
		String assetType = asset.getAssetType();
		
		if(assetType == null || assetType.length() < 2) { 
			return "CMXX"; 
		}
		else {
			return "CM" + assetType.substring(0,2);
		}
	}
	
	private String getNewId() {
		// sleeping forcefully or else, we may end up with multiple assets with the same id  
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// this should not happen
		}

		// Get time
		long t = System.currentTimeMillis();
		
		// Get host IP address
		String hostId = getHostId();
		if(hostId == null) hostId = IP_LOCALHOST;
		
		// Get last IP subnet
		String subnet = null;
		try {
			subnet = hostId.substring(hostId.lastIndexOf('.') + 1);
		}
		catch(Exception ex) {
		}
		if(subnet == null) subnet = "1";
		

		// Create ID
		String IDString = subnet + t;
		t = Long.parseLong(IDString);
		
		DecimalFormat df = new DecimalFormat();
		df.setMinimumIntegerDigits(16);
		String pattern = "0000000000000000";
		df.applyPattern(pattern);
		
		return df.format(t);
	}

	private String getHostId() {
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();  
			return inetAddress.getHostAddress();
		}
		catch(Exception ex) {
			return IP_LOCALHOST;
		}
	}

}
