/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.awk.builtin.t;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import net.morilib.awk.io.AwkFiles;
import net.morilib.awk.namespace.AwkNamespace;
import net.morilib.awk.value.AwkFunction;
import net.morilib.awk.value.AwkInteger;
import net.morilib.awk.value.AwkValue;

/**
 * 関数t.timeの記述です。
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/04/13
 */
public class TTime extends AwkFunction {

	protected TTime() {
		super("time", null);
	}

	@Override
	public AwkValue apply(AwkNamespace ns, AwkFiles o,
			List<AwkValue> a) {
		GregorianCalendar c = new GregorianCalendar();
		int ye, mo, da, ho, mi, se, ms, zo, zd;
		long r;

		if(a.size() < 1) {
			r = new java.util.Date().getTime();
		} else {
			zd = TimeZone.getDefault().getRawOffset() / 3600000;
			ye = a.get(0).toIntExact();
			mo = a.size() < 2 ?  1 : a.get(1).toIntExact();
			da = a.size() < 3 ?  1 : a.get(2).toIntExact();
			ho = a.size() < 4 ?  0 : a.get(3).toIntExact();
			mi = a.size() < 5 ?  0 : a.get(4).toIntExact();
			se = a.size() < 6 ?  0 : a.get(5).toIntExact();
			ms = a.size() < 7 ?  0 : a.get(6).toIntExact();
			zo = a.size() < 8 ? zd : a.get(7).toIntExact();
			c.set(Calendar.YEAR, ye);
			c.set(Calendar.MONTH, mo - 1);
			c.set(Calendar.DAY_OF_MONTH, da);
			c.set(Calendar.HOUR_OF_DAY, ho + (zo - zd));
			c.set(Calendar.MINUTE, mi);
			c.set(Calendar.SECOND, se);
			c.set(Calendar.MILLISECOND, ms);
			r = c.getTimeInMillis();
		}
		return AwkInteger.valueOf(r);
	}

}
