/*
 * 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.frames.mainframe.impl;

import com.queplix.core.client.app.rpc.RPC;
import com.queplix.core.client.app.vo.FieldData;
import com.queplix.core.client.app.vo.SavedSearchObject;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.i18n.I18N;

import java.util.Collection;
import java.util.Iterator;

/**
 * Save current search or load a saved search
 *
 * @author Alexander Epifanov, Vasily Mikhailitchenko
 */
class SavedSearch {
    public static interface Events {
        Event DONE = new Event();
        Event LOADED = new Event();
        Event RENAME = new Event();
        Event ERROR = new Event();
    }

    private class LoadSavedSearchesAsyncCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                saved = (SavedSearchObject[]) result;
                fireEvent(SavedSearch.Events.LOADED);
            } else {
                fireEvent(SavedSearch.Events.ERROR);
            }
        }
    }

    private class SaveSearchAsyncCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                fireEvent(SavedSearch.Events.DONE);
            } else {
                fireEvent(SavedSearch.Events.ERROR);
            }
        }
    }

    private class PrepareToSaveSearchAsyncCallback extends RPC.QAsyncCallback {
        private SavedSearchObject search;

        public PrepareToSaveSearchAsyncCallback(SavedSearchObject search) {
            this.search = search;
        }

        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                saved = (SavedSearchObject[]) result;
                doSave(search);
            } else {
                fireEvent(SavedSearch.Events.ERROR);
            }
        }

        protected void handleError(Throwable error) {
            //do nothing otherwise it will show 2 messages
        }
    }

    private SavedSearchObject[] saved;
    private EventListener eventListener;

    /**
     * Creates a new instance of SavedSearch
     */
    public SavedSearch() {
    }

    public void addEventListener(EventListener eventListener) {
        this.eventListener = eventListener;
    }

    private void fireEvent(Event event) {
        if(null != this.eventListener) {
            this.eventListener.onEvent(event, null);
        }
    }

    public void save(String name, String formId, FieldData[] filters) {
        SavedSearchObject search = new SavedSearchObject(name, formId, filters,
                null);
        RPC.getRPC().loadSavedSearches(new PrepareToSaveSearchAsyncCallback(
                search));
    }

    private void doSave(SavedSearchObject search) {
        Long rowIDToOverwrite = null;

        for(int i = 0; i < saved.length; i++) {
            if(saved[i].getSearchName().equals(search.getSearchName())) {
                rowIDToOverwrite = saved[i].getRowID();
                break;
            }
        }

        if(rowIDToOverwrite != null) {
            int answer = DialogHelper.showModalQuestionDialog(
                    I18N.getMessages().searchNameExistsOverwrite());
            if(answer == DialogHelper.YES) {
                search.setRowID(rowIDToOverwrite);
                RPC.getRPC().saveSearch(search, new SaveSearchAsyncCallback());
            } else if(answer == DialogHelper.NO) {
                fireEvent(SavedSearch.Events.RENAME);
            }
        } else {
            RPC.getRPC().saveSearch(search, new SaveSearchAsyncCallback());
        }
    }

    public void load() {
        RPC.getRPC().loadSavedSearches(new LoadSavedSearchesAsyncCallback());
    }

    public SavedSearchObject loadSearch(String name) {
        for(int i = 0; i < this.saved.length; i++) {
            if(name.equals(this.saved[i].getSearchName())) {
                return this.saved[i];
            }
        }
        return null;
    }

    public SavedSearchObject[] getSavedSearches() {
        return this.saved;
    }

}


