/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.client.controls.datefield;

import com.queplix.core.client.app.rpc.RPC;
import com.queplix.core.client.app.vo.FormatDataRequestObject;
import com.queplix.core.client.app.vo.FormatDataResponseObject;
import com.queplix.core.client.common.ui.DialogHelper;

import java.util.Date;

/**
 * Data Formatter.
 *
 * @author Aliaksandr Melnik
 * @since 22 Nov 2006
 */
public class DateFormatter {
    private FormatDataRequestObject request = new FormatDataRequestObject();

    private DataFormatterListener dataFormatterListener;//only one listener

    public void addDataFormatterListener(DataFormatterListener listener) {
        dataFormatterListener = listener;
    }

    public DateFormatter() {
    }

    public void format(Date date) {
        request.setStartDate(date);
        request.setEndDate(null);
        RPC.QAsyncCallback callback = new FormateDateAsyncCallback();
        RPC.getRPC().formatDate(request, callback);
    }

    public void format(Date startDate, Date endDate) {
        request.setStartDate(startDate);
        request.setEndDate(endDate);
        RPC.QAsyncCallback callback = new FormateDateAsyncCallback();
        RPC.getRPC().formatDate(request, callback);
    }

    private class FormateDateAsyncCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                FormatDataResponseObject fdro
                        = (FormatDataResponseObject) result;
                dataFormatterListener.formated(fdro.getFormatedDate());
            } else {
                dataFormatterListener.formatFailed();
                DialogHelper.showModalMessageDialog(
                        "Format Date Request Failed.");
            }
        }
    }

    public interface DataFormatterListener {
        public void formated(String date);

        public void formatFailed();
    }

}
