import { BX24Server } from "./BX24Server";
import { set as __set } from "lodash";
import { AuthBaseDev } from "./types/authBaseDev";


export class BX24Dev extends BX24Server{
    constructor(param: AuthBaseDev, cb?:()=>void){
        super(param);

        this.init(()=>{
            this.callBatch({
                getAppOption:['app.option.get', {}],
                getUserOption:['user.option.get', {}]
            }, ress=>{
                let idx: keyof typeof ress;
                let textError='';
                for (idx in ress){
                    const res=ress[idx];
                    if (res.error()){
                        textError+=`Init error. Check auth data. ${res.error()} for ${idx}\n`;
                    }
                    else{
                        if (idx=='getAppOption'){
                            this.APP_OPTIONS=res.data();
                        }
                        else{
                            this.USER_OPTIONS=res.data();
                        }
                    }
                }
                if (textError)
                    console.error(textError);
                    
                if (cb){
                    cb();
                }
            })
            this.getPlacementOptions();
        });

        if (new Date().getTime()-5*60*1000>this.AUTH_EXPIRES && !param.noUpdateRefresh){
            this.refreshAuthAsync().then(()=>{
                this.doInit();
            })
            .catch((error:Error)=>{
                this.logger.error(error);
            });
        }
        else{            
            this.doInit();
        }
    }


    appOption={
		get: (name:string)=>{
			return this.APP_OPTIONS[name];
		},
		set:(name:string,value:any,cb:(params:any)=>void)=>{
            if (this.isAdmin()){
                const params:{[key:string]:any}={};
                params[name]=value;
                this.callMethod('app.option.set', params, res=>{
                    if (res.data()===true){
                        this.APP_OPTIONS[name] = value;
                    }
                    if (cb){
                        cb(res);
                    }
                })
            }
			else{
                console.error('Access denied!');
            }
		}
	}

    userOption={
        get:(name:string)=>{
            return this.USER_OPTIONS[name];
        },
        set:(name:string, value:any,cb:(params:any)=>void)=>{
            const params:{[key:string]:any}={};
            params[name]=value;
            this.callMethod('user.option.set', params, res=>{
                if (res.data()===true){
                    this.USER_OPTIONS[name] = value;
                }
                if (cb){
                    cb(res);
                }
            });
        }
    }

    private getPlacementOptions(){
        const result:{[key:string]:any}={};
        const url=typeof location!=='undefined'?new URL(location.href) as any:undefined;
        const entrity=url?url.searchParams.entries():undefined;
        const regexp=/\[([^\]]*)]/g;
        let done=entrity?false:true;
        while(!done){
            const el=entrity.next();
            done=el.done===true?true:false;
            if (el.value){
                let tempArrPath=Array.from(el.value[0].matchAll(regexp)) as string[];
                tempArrPath=tempArrPath.map(ell=>{return ell[1]});
                const base=el.value[0].split('[')[0];
                __set(result, [base, ...tempArrPath], el.value[1]);
            }
        }

        if (result.placement){
            this.PLACEMENT=result.placement;
            delete(result.placement);
        }
        else{
            this.PLACEMENT='DEFAULT';
        }

        this.PLACEMENT_OPTIONS=result;
    }

    openApplication(params?:Record<string, string|number>, cb?:(params:any)=>void, settings?:any):void{
        if (!params){
            params={};
        }

        if (settings&&typeof(settings)=='object'){
            for (const item in settings){
                params["bx24_" + item]=settings[item];
            }
        }


        window.open(`?${this.getHttpString(params)}`);
        console.log(`На проде по закрытии слайдера, я запущу функцию`, cb);
    }

    openPath(path:string, cb?:(params:any)=>void):void{
        window.open(`${this.PROTOCOL?'https:':'http'}${this.DOMAIN}${path}`);
        console.log(`На проде по закрытии слайдера, я запущу функцию`, cb);
    }
}