package org.mariadb.jdbc;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TimezoneTest extends BaseTest {

    private Statement statement;
    private Locale previousFormatLocale;
    private TimeZone previousTimeZone;
    private TimeZone atlanticOceanTimeZone;
    private TimeZone utcTimeZone;
    private SimpleDateFormat utcDateFormatISO8601;
    private SimpleDateFormat utcDateFormatSimple;
    private Calendar _1320;
    private String _1320String;

    @Before
    public void setUp() throws SQLException {
        //Save the previous FORMAT locate so we can restore it later
        previousFormatLocale = Locale.getDefault();
        //Save the previous timezone so we can restore it later
        previousTimeZone = TimeZone.getDefault();
        
        //Since many of the internal driver code (for example SimpleDateFormat) uses the
        //java default timezone, lets change it for this test cases to something unlikely that a
        //test runner have: GMT -2. There are practically no one living in GMT -2 since
        //it is the Atlantic Ocean.
        atlanticOceanTimeZone = TimeZone.getTimeZone("GMT-2:00");
        TimeZone.setDefault(atlanticOceanTimeZone); 

        //I have tried to represent all times written in the code in the UTC time zone
        utcTimeZone = TimeZone.getTimeZone("utc");
        
        //Use a date formatter for UTC timezone in ISO 8601 so users in different
        //timezones can compare the test results easier.
        utcDateFormatISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        utcDateFormatISO8601.setTimeZone(utcTimeZone);
        
        utcDateFormatSimple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        utcDateFormatSimple.setTimeZone(utcTimeZone);

        //ReInitialize the connection (to make sure it uses our new GMT -2 timezone) 
        connection.close();
        before();
        
        statement = connection.createStatement();
        statement.execute("drop table if exists timestamptest");
        statement.execute("create table timestamptest (id int not null primary key auto_increment, tm timestamp)");
        
        //I'm using a the time 13:20 in UTC as example
        _1320 = Calendar.getInstance(utcTimeZone);
        _1320.clear();
        _1320.set(2014, 0, 1, 13, 20, 59);
        _1320String = utcDateFormatISO8601.format(new Date(_1320.getTimeInMillis()));
    }
    
    @After
    public void tearDown() {
        //Reset the FORMAT locate so other test cases are not disturbed.
        Locale.setDefault(previousFormatLocale);
        //Reset the timezone so so other test cases are not disturbed.
        TimeZone.setDefault(previousTimeZone);
    }
    
    @Test
    public void testGetTimestampTest() throws SQLException {
        //I think this kind of insert only works for servers in UTC. So this test case should
        //probably be removed if this file is included in MariaDB JDBC source tree.
        PreparedStatement ps = connection.prepareStatement("insert into timestamptest values(1, FROM_UNIXTIME(?))");
        ps.setLong(1, _1320.getTimeInMillis()/1000);
        ps.execute();
        
        //Verify with ResultSet.getTimestamp() that it is correct
        ResultSet rs = statement.executeQuery("select * from timestamptest");
        assertTrue(rs.next());
        Timestamp timestamp = rs.getTimestamp("tm");
        assertEquals(_1320String, utcDateFormatISO8601.format(timestamp));
    }
    
    @Test
    public void testEnsureServerIsNotUsingAtlanticTimeZone() throws SQLException {
        assertFalse("These test cases are designed to show error in the code depending on server "
            + "timezone. You can use any timezone for the server except GMT -02:00. Are you really in "
            + "the middle of the Atlantic Ocean?", 
            getSessionTimeZone().equals("-02:00"));
    }
    
    @Test
    public void testGetTimestampAdvancedTimeZoneSwitching() throws SQLException {
        String previousSessionTimeZone = getSessionTimeZone();
        
        //Force session to use UTC time
        setSessionTimeZone(connection, "+00:00");
        Statement statement = connection.createStatement();
        
        //Use the "wrong" way to insert a timestamp: as a string. This is done to avoid bugs in
        //the PreparedStatement.setTimestamp(int parameterIndex, Timestamp x) method and to make
        //sure the value is a correct 13:20 UTC time.
        statement.execute("insert into timestamptest values(1, '" 
                        + utcDateFormatSimple.format(new Date(_1320.getTimeInMillis())) + "')");
        
        setSessionTimeZone(connection, previousSessionTimeZone);
        
        //Verify with ResultSet.getTimestamp() that it is correct
        ResultSet rs = statement.executeQuery("select * from timestamptest");
        assertTrue(rs.next());
        Timestamp timestamp = rs.getTimestamp("tm");
        assertEquals(_1320String, utcDateFormatISO8601.format(timestamp));
    }
    
    /**
     * Return the session timezone in a "+02:00" or "-05:00" format. 
     */
    private String getSessionTimeZone() throws SQLException {
        ResultSet resultSet = statement.executeQuery(
            "select CONVERT(timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00')), CHAR)");
        
        resultSet.next();
        
        String timeZoneString = resultSet.getString(1);
        
        timeZoneString = timeZoneString.replaceAll(":00$", "");
        
        if (!timeZoneString.startsWith("-")) {
            timeZoneString = "+" + timeZoneString;
        }
        
        return timeZoneString;
    }
    
    private void setSessionTimeZone(Connection connection, String timeZone) throws SQLException {
        Statement statement = connection.createStatement();
        statement.execute("set @@session.time_zone = '" + timeZone + "'");
        statement.close();
    }
    
}

