package com.yeejoin.amos.iec104.tcp.entity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.coyote.http2.ByteUtil;

import io.netty.buffer.ByteBuf;

public class IeCP56Time2a extends InformationElement{

	protected byte[] date = new byte[7];
	// test
//	protected byte[] date = { (byte) 0xAD, (byte)0x39 , (byte)0x1C, (byte)0x10, (byte)0x7A , (byte)0x0B, (byte)0x05};
	
	public IeCP56Time2a(ByteBuf is) throws IOException {
		if (is.readableBytes() > 7) {
			is.readBytes(date);
		}
    }
	public IeCP56Time2a() {
		
	}
	
	@Override
	public int encode(byte[] buffer, int i) {
		return 1;
	}

	public Date getDate() {
		int handleS = ByteUtil.getTwoBytes(date, 0);
		int second = handleS / 1000;
		int milliSecond = handleS % 1000;
		int minute = ByteUtil.getOneByte(date, 2);
		int hour = ByteUtil.getOneByte(date, 3);
		int day = ByteUtil.getOneByte(date, 4);
		int month = ByteUtil.getOneByte(date, 5);
		int year = ByteUtil.getOneByte(date, 6);
		
		String yearStr = Integer.toHexString(year);
		yearStr = yearStr.length() > 1?yearStr:"0".concat(yearStr);
        Calendar calendar = new GregorianCalendar();
        year = Integer.parseInt(String.valueOf(calendar.get(Calendar.YEAR)).substring(0, 2) + yearStr);

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DATE, day);
		cal.set(Calendar.HOUR_OF_DAY, hour);
		cal.set(Calendar.MINUTE, minute);
		cal.set(Calendar.SECOND, second);
		cal.set(Calendar.MILLISECOND, milliSecond);
		return cal.getTime();
	}
	
	public String getFormatDate(String pattern) {
		Date d = getDate();
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(d);
	}
	
//	public static void main(String[] args) {
//		IeCP56Time2a a = new IeCP56Time2a();
//		Date d = a.getDate();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		System.out.println(sdf.format(d));
//	}
}
