/*
 * Copyright (c) 2010-2024 Belledonne Communications SARL.
 *
 * This file is part of Linphone Java Tutorial.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package controller;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import service.CoreService;

import org.linphone.core.Account;
import org.linphone.core.Core;
import org.linphone.core.CoreListenerStub;
import org.linphone.core.RegistrationState;

public class LoginController extends CoreListenerStub implements Initializable, ScreenInterface {
    @FXML
    private Button loginButton;
    @FXML
    private TextField identityField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Label registrationLabel;

    private CoreService coreService = CoreService.instance();

    @FXML
    public void initialize(URL location, ResourceBundle resourceBundle) {
        coreService.start();
    }

    @FXML
    private void onLoginClicked() {
        if (loginButton.isDisabled())
            return;
        loginButton.setDisable(true);
        coreService.login(identityField.getText(), passwordField.getText());
    }

    @Override
    public void onAccountRegistrationStateChanged(Core core, Account account, RegistrationState state, String message) {
        registrationLabel.setText("Your registration state is: " + state.toString());
        switch (state) {
            case Cleared:
            case None:
                coreService.clearCoreAfterLogout();
                loginButton.setDisable(false);
                break;
            case Ok:
                loginButton.setDisable(true);
                coreService.screenController.activate("call");
                break;
            case Progress:
                loginButton.setDisable(true);
                break;
            case Failed:
                loginButton.setDisable(false);
                break;
            default:
                break;
        }
    }

    @Override
	public void onNavigatedFrom() {
        coreService.core.removeListener(this);
	}

	@Override
	public void onNavigatedTo() {
        coreService.core.addListener(this);
	}
}
