import JSONModel from "sap/ui/model/json/JSONModel";
import BaseController from "./BaseController";

/**
 * @namespace com.optrabot.ui.controller
 */
export default class Settings extends BaseController {
	private oViewModel: JSONModel;

	public onInit(): void {
		console.log("Settings controller initialized");
		this.oViewModel = new JSONModel({
			tastytradeSandbox: false,
			tastytradeClientId: ""
		});
		this.getView().setModel(this.oViewModel, "oViewModel");
	}

	public onAuthorizePress(): void {
		const globalModel = this.getOwnerComponent().getModel("global") as JSONModel;
		const redirectUri = `${globalModel.getProperty("/backendBaseUrl")}/auth/tasty_callback`;
		const clientId = this.oViewModel.getProperty("/tastytradeClientId");
		const authUrl = `${this.getTastytradeAuthUrl()}?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code`;
		window.open(authUrl, 'tastyauth', 'width=500,height=500');
	}

	private getTastytradeAuthUrl(): string {
		const isSandbox = this.oViewModel.getProperty("/tastytradeSandbox");
		return isSandbox ? "https://cert-my.staging-tasty.works/auth.html" : "https://my.tastytrade.com/auth.html";
	}
	
}