/*
 * @(#)LiaisonVANParser.java
 *
 * Copyright (c) 2017 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 */
package com.jscape.inet.ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Parser responsible for handling proprietary directory listing returned by
 * Liaison VAN FTP server. The following is a partial example listing of the
 * format expected.
 * <p/>
 * <p/>
 * <pre>
 * Type Doc   Control #     Sender ID              Size Date/Time Message ID
 * ISA 850    2             ZZSASTESTUSF            809 0407/1413 SASTESTUSF.9.1
 * ISA 850    2             ZZSASTESTUSF            809 0407/1413 SASTESTUSF.A.1
 * ISA 850    2             ZZSASTESTUSF            809 0410/0859 SASTESTUSF.B.1
 * </pre>
 */
@SuppressWarnings("unchecked")
public class LiaisonVANParser
        implements FtpFileParser {
    private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

    // Unix Parser locale
    private Locale currentLocale = Locale.US;

    /**
     * Parses directory listing. Reads directory listing from FTP server and
     * parses contents into an Enumeration of FtpFile.
     *
     * @param in the BufferedReader passed in by Ftp class when invoking
     *           Ftp#getDirListing method.
     *
     * @return an Enumeration of FtpFile
     *
     * @see FtpFile
     * @see Ftp#getDirListing
     */
    public Enumeration parse(BufferedReader in)
            throws IOException {
        Vector files = new Vector();

        String line = "";

        while ((line = in.readLine()) != null) {
            FtpFile file = parseLine(line);
            if (file != null) {
                files.addElement(file);
            }
        }

        return files.elements();
    }

    /**
     * Gets the date and time for an FtpFile entry sourced from a UNIX directory
     * listing.
     *
     * @param file   the FtpFile
     * @param zone   the TimeZone to use when calculating time. Your default
     *               timezone is used if not provided.
     * @param locale the Locale to use when parsing date. Locale.US is used if not
     *               provided.
     *
     * @return a Date, or null if FtpFile#getDate or FtpFile#getTime values are
     *         null
     *
     * @throws ParseException if an error occurs while parsing entry
     * @see java.util.TimeZone
     * @see java.util.Locale
     * @see FtpFile
     */
    public Date getDateTime(FtpFile file, TimeZone zone, Locale locale)
            throws ParseException {
        Date d = null;
        SimpleDateFormat df = null;

        try {

            // set locale
            if (locale != null) {
                df = new SimpleDateFormat("MMM d HH:mm", locale);
            } else {
                df = new SimpleDateFormat("MMM d HH:mm", Locale.US);
            }

            // set timezone
            if (zone != null) {
                df.setTimeZone(zone);
            }

            d = df.parse(file.getDate() + " " + file.getTime());
            Calendar cal = new GregorianCalendar();
            int currentYear = cal.get(GregorianCalendar.YEAR);
            cal.setTime(d);
            cal.set(GregorianCalendar.YEAR, currentYear);
            d = adjustYear(cal.getTime(), cal, currentYear);

        } catch (ParseException e) {
            if (locale != null) {
                df = new SimpleDateFormat("MMM d yyyy HH:mm", locale);
                d = df.parse(file.getDate() + " " + file.getTime());
            } else {
                df = new SimpleDateFormat("MMM d yyyy HH:mm", Locale.US);
                d = df.parse(file.getDate() + " " + file.getTime());
            }
        }
        return d;
    }

    /**
     * Adjust year.
     *
     * @param date
     * @param currentYear
     *
     * @return modified Date instance.
     */
    private Date adjustYear(Date date, int currentYear) {
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.MONTH) > currentCal.get(Calendar.MONTH)) {
            calendar.set(GregorianCalendar.YEAR, currentYear - 1);
            date = calendar.getTime();
        }
        return date;
    }

    /**
     * Sets year for FtpFile entries that do not have year information
     *
     * @param date
     * @param calendar
     * @param currentYear
     *
     * @return
     */
    private Date adjustYear(Date date, Calendar calendar, int currentYear) {
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(new Date());
        if (date.after(new Date())) {
            calendar.set(GregorianCalendar.YEAR, currentYear - 1);
            date = calendar.getTime();
        }
        return date;
    }

    /**
     * Gets the date and time for an FtpFile entry sourced from a UNIX directory
     * listing.
     *
     * @param file the FtpFile
     *
     * @throws ParseException if an error occurs while parsing entry
     * @see FtpFile
     */
    public Date getDateTime(FtpFile file)
            throws ParseException {
        return getDateTime(file, null, null);
    }

    public FtpFile parseLine(String line) {
        try {
            StringReader reader = new StringReader(line);
            String permissions = "";

            String type = readField(reader); //Type
            String group = readField(reader); //Doc
            String control = readField(reader); //Control #
            
            String owner = readField(reader); //Sender ID
            long size = readSize(reader); //Size
            String[] dateSlashTime = readField(reader).split("/"); //Date/Time
            String name = readField(reader) + "." + type; //Message ID
            String link = "";


            return new FtpFile(name,
                               size,
                               owner,
                               group,
                               permissions,
                               toUnixDate(dateSlashTime[0]),
                               toUnixTime(dateSlashTime[1]),
                               false,
                               false,
                               link,
                               0,
                               line,
                               false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private char skipWhiteSpace(StringReader reader)
            throws Exception {
        int ch;
        while ((ch = reader.read()) != -1 && Character.isWhitespace((char) ch)) {
            // ok
        }
        return (char) ch;
    }

    private String readField(StringReader reader)
            throws Exception {
        StringBuffer buf = new StringBuffer();
        int ch;
        buf.append(skipWhiteSpace(reader));
        while ((ch = reader.read()) != -1 && !Character.isWhitespace((char) ch)) {
            buf.append((char) ch);
        }
        return buf.toString();
    }

    private long readSize(StringReader reader)
            throws Exception {
        StringBuffer buf = new StringBuffer();
        int ch;
        buf.append(skipWhiteSpace(reader));
        while ((ch = reader.read()) != -1 && !Character.isWhitespace((char) ch)) {
            buf.append((char) ch);
        }

        if (ch == -1) {
            throw new Exception("Unexpected EOF.");
        }

        String num = buf.toString();
        return Long.parseLong(num);
    }

    private String toUnixDate(String mmdd) {
        int monthIndex = Integer.valueOf(mmdd.substring(0, 2));
        return MONTHS[monthIndex - 1] + " " + mmdd.substring(2);
    }

    private String toUnixTime(String hhmm) {
        return hhmm.substring(0, 2) + ":" + hhmm.substring(2);
    }
    
    /**
     * Parses a string which contains a date and returns a date object
     *
     * @param date The string will be parsed
     *
     * @return A object date which corresponds with the input string argument
     *
     * @throws ParseException if an error ocurrs
     */
    public Date getFileDate(String date)
            throws ParseException {
        // Entry Format spected
        // Jul 23
        Date fileDate = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("MMM d", Locale.US);
            fileDate = format.parse(date);
            Calendar fileCalendar = Calendar.getInstance();
            fileCalendar.setTime(fileDate);
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            fileCalendar.set(Calendar.YEAR, year);
            fileDate = adjustYear(fileCalendar.getTime(), fileCalendar, year);
        } catch (ParseException e) {
            SimpleDateFormat format = new SimpleDateFormat("MMM dd", Locale.US);
            fileDate = format.parse(date);
            Calendar fileCalendar = Calendar.getInstance();
            fileCalendar.setTime(fileDate);
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            fileCalendar.set(Calendar.YEAR, year);
            fileDate = adjustYear(fileCalendar.getTime(), fileCalendar, year);
        }
        return fileDate;
    }

    /**
     * Sets locale used for parsing date.
     *
     * @param locale the locale
     */
    public void setLocale(Locale locale) {
        this.currentLocale = locale;
    }
}
