package tst

import (
	"fmt"

	. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
	TS "git.eugeniocarvalho.dev/eugeniucarvalho/gg/generators/typescript"
)

var (
	module *TS.File
)

func Translate(project *Project) (err error) {

	ts := project.Client("angular6")

	path := fmt.Sprintf("%s/%s.module.ts", ts.OutputDir, project.ID)
	// Write(fmt.Sprintf("%s/%s/params.go", p.OutPath, p.Package), file)
	module = TS.NewFile(path)

	// Adiciona os importes necessarios
	imports(project, module)

	// Cria todas as classes de entidades do projeto
	if err = GenSchemas(project); err != nil {
		return
	}
	// Define os objetos de acesso a API
	GenResources(project)

	return module.Save()
}

func imports(project *Project, file *TS.File) {

	file.Raw(`
	// import { NgModule, Injectable, EventEmitter, ModuleWithProviders } from '@angular/core';
	import { NgModule, Injectable, EventEmitter, ModuleWithProviders, InjectionToken, Inject } from '@angular/core';
	// import { BrowserModule } from '@angular/platform-browser';
	import { CommonModule } from '@angular/common';
	import { HttpClientModule, HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
	import { Observable, of, Subject, BehaviorSubject} from 'rxjs';
	// import { ActivatedRoute, Router } from '@angular/router';
	import { catchError, map, switchMap, tap, take, filter } from 'rxjs/operators';
	import { EventSourcePolyfill } from 'event-source-polyfill';
	
	if (!Boolean(window['oauth_ss'])) {
		window['oauth_ss'] = Math.random().toString(30).substr(2, 11).toUpperCase();
	}
	
	const oauthWindowProp = `).Raw(fmt.Sprintf("`__${window['oauth_ss']}__`")).Raw(`;

	// @Injectable({
	// 	providedIn: 'root'
	// })
	export class `).Raw(project.Name + "ApiOptions").Raw(` {
		public COOKIE_DOMAIN:string;
		public BASE_URL:string;
		public ACCOUNT_URL:string;
		public CONSOLE_URL:string;
		public REDIRECT_URI:string;
		public CLIENT_ID:string;
		public THREAD_SOCKET:string;
		public CLIENT_SECRET:string;
		public SCOPES: string[];
		
	}

	export const ApiOptionsParams = new InjectionToken<`).Raw(ApiClassName(project) + "Options").Raw(`>('ApiOptionsParams');

	export interface ApiInterface {
		Client: Client;
		Auth: Auth;
		poolReady: any[];
		httpOptions: {
			headers: HttpHeaders,
			withCredentials: boolean,
			};
		http: HttpClient;
		// queryParams: any;
		// route: ActivatedRoute;
		// router: Router;
		apiOptions: any;
		options(opts?: HttpOptions): HttpOptions;
		onready(fn: () => void);
		copyHeader(headers, hopts);
	}
	
	`).Line()
}

func getCustom(options map[string]interface{}, path string) (resp interface{}) {
	if options != nil {
		resp = options[path]
	}
	return
}
